Twig loop index into array
57,897
Solution 1
{% for com in comments %}
<p>Comment {{ nameComments[ loop.index ] }} : "{{ com['comment'] }}"</p>
{% endfor %}
Just leave out the curly brackets. This should work fine.
By the way loop.index
is 1 indexed. If you loop through an array which normally starts with index 0 you should consider using loop.index0
See the documentation
Solution 2
It is safer to iterate over the real value of the array index and not using loop.index and loop.index0 in case where array indexes do not start in 1 or 0 or do not follow a sequence, or they are not integers.
To do so, just try this:
{% for key,com in comments %}
<p>Comment {{ nameComments[key] }} : "{{ com['comment'] }}"</p>
{% endfor %}
See the documentation
Comments
-
keegzer over 2 years
I want to show my string value into my array 'nameComments' with key
{{loop.index}}
of my comments array, but{{ nameComments[{{ loop.index }}] }}
show an error{% for com in comments %} <p>Comment {{ nameComments[{{ loop.index }}] }} : "{{ com['comment'] }}"</p> {% endfor %}
If I try:
{% for com in comments %} <p>Comment {{ nameComments[1] }} : "{{ com['comment'] }}"</p> {% endfor %}
And the
{{ loop.index }}
show me value :1
So how can I implement my loop index into my array?
-
Romain Bruckert about 7 yearsExcellent to take note of
loop.index0
. This can get you crazy when you forget about that !! ;-)