keegzer
keegzer

Reputation: 524

Twig loop index into array

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?

Upvotes: 26

Views: 86774

Answers (2)

SirDerpington
SirDerpington

Reputation: 11460

{% 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

Upvotes: 45

Abraham Covelo
Abraham Covelo

Reputation: 961

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

Upvotes: 10

Related Questions