26

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent to take note of loop.index0. This can get you crazy when you forget about that !! ;-)
11

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.