2

According to the documentation on for loops, you can access some special variables inside of a for loop like "loop.index". Is there a way to specify which loop we want to refer to?

For example say we have a double for loop like so:

   {% for row in rows %} --OUTER LOOP
       <tr>
            {% for column in Columns %} -- INNER LOOP
                <td>{{ row[column] }} {{loop.index}}</td>
            {% endfor %}
       </tr>
   {% endfor %}

Say I want {{loop.index}} to refer to the OUTER LOOP or the INNER LOOP. How can I distinguish which one it will refer to? Is this possible?

Luca Guarro
  • 1,085
  • 1
  • 11
  • 25
  • Does this answer your question? [In a nested for-loop, how can I access the outer loop index in a jinja template?](https://stackoverflow.com/questions/37110114/in-a-nested-for-loop-how-can-i-access-the-outer-loop-index-in-a-jinja-template) – Timothy James Feb 07 '23 at 00:48

1 Answers1

0

I think I found my answer which is you cannot use the loop special variables to reference the outer loop when you are in the inner loop. As a workaround, one can set a counter variable for each loop.

   {% set outer_index = namespace(value=0) %}
   {% for row in rows %} --OUTER LOOP
       <tr>
            {% for column in Columns %} -- INNER LOOP
                {% set inner_index = namespace(value=0) %}
                <td>{{ row[column] }} {{outer_index.value}}</td>
                {% set inner_index.value = count.value + 1 %}
            {% endfor %}
       </tr>
       {% set outer_index.value = count.value + 1 %}
   {% endfor %}
Luca Guarro
  • 1,085
  • 1
  • 11
  • 25
  • 1
    Alternatively, you can assign the whole `loop` variable, as pointed in the documentation: https://jinja.palletsprojects.com/en/3.0.x/tricks/#accessing-the-parent-loop – β.εηοιτ.βε Sep 02 '22 at 06:50