In Jinja, how do you reference outer for loop in a nested for loop

Viewed 37

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?

1 Answers

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