Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access loop.index when within another loop in twig

Tags:

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 %}
like image 478
Rachid O Avatar asked Sep 11 '13 00:09

Rachid O


2 Answers

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

Also refer to the documentation

like image 169
SirDerpington Avatar answered Nov 06 '22 08:11

SirDerpington


set a variable which hold the first loop.index

{% for i in range(0, 3) %}
    {% set loop1 = loop.index %}
    {% for j in range(0, 9) %}
        {{ loop1 + loop.index }}
    {% endfor %}
{% endfor %}
like image 45
ihsan Avatar answered Nov 06 '22 08:11

ihsan