63

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 %}
2
  • 1
    What is the application of this summation? Commented Jan 12, 2017 at 7:50
  • @Trix maybe to process linearly a two-dimensional stuff (like image processing): j being the column index while i being the row index Commented Oct 29, 2018 at 10:12

2 Answers 2

135

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

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

1 Comment

You can continue stacking loop.parent if needed. Here's an example of three levels: twigfiddle.com/b8skwh
4

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

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.