Rachid Oussanaa Rachid Oussanaa - 2 months ago 32
Twig Question

access loop.index when within another loop in twig

How can i access the loop's index when i'm in a second loop? like this:

{% for i in range(0, 3) %}
{% for j in range(0, 9) %}
{{ loop1.index + loop2.index }} // ?
{% endfor %}
{% endfor %}

Answer

In fact there's no need to set an extra variable. For two nested loops twig provides the so called parent.loop context.

To access the parents loop.index do this:

{% for i in range(0, 3) %}
    {% for j in range(0, 9) %}
        {{ loop.parent.loop.index + loop.index }}
    {% endfor %}
{% endfor %}

Those two documentation entries should be helpful