[...]
contains several {...}
Objects.
Like this example:
[{ "id" : 1696, "title" : "1Experiment Your Way Through Change", "type" : 14}, { "id" : 2696, "title" : "2Experiment Your Way Through Change", "type" : 24} ]To loop through the Objects you can use “_context” in the twig-template:
{% for key, value in _context %} key: {{key}}The result is not exactly what you expect! The loop runs through three items, not the two of the JSON. The 3rd item is the complete JSON.
value: {{value | json_encode}}
id: {{value.id}}
{% endfor %}
Alter the twig-template by replacing _context by _parent:
{% for key, value in _parent %} key: {{key}}Result: Only the two expected items. But…
value: {{value | json_encode}}
id: {{value.id}}
{% endfor %}
If you do some additional twig in the template, esp. adding a variable this is added to _parent and _context. Try this:
{% set aVariable="whatever" %} {% for key, value in _context %} key: {{key}}The result: Four items! The Variable created by “set” is added to _context and is thus available in the twig-template by “_context.aVariable” and “aVariable”. As you only want two items, you must separate the wanted from the unwanted items by a if-statement like this:
value: {{value | json_encode}}
id: {{value.id}}
{% endfor %} aVariable: {{ _context.aVariable}}
{% set aVariable="whatever" %} {% for key, value in _context %} {% if value.id %} key: {{key}}
value: {{value | json_encode}}
id: {{value.id}}
{% endif %} {% endfor %}
In Action:
key: 0
value: {“id”:1696,”title”:”1Experiment Your Way Through Change”,”type”:14}
id: 1696
key: 1
value: {“id”:2696,”title”:”2Experiment Your Way Through Change”,”type”:24}
id: 2696