Get the outer loop cycle index

In jinja, the loop.index variable contains the iteration number of the current current loop.

When I have nested loops, how can I get the current iteration of the outer loop in the inner loop?

+45
template-engine jinja2
Oct 14 '09 at 15:59
source share
2 answers

Save it in a variable, for example:

{% for i in a %} {% set outer_loop = loop %} {% for j in a %} {{ outer_loop.index }} {% endfor %} {% endfor %} 
+69
Oct 14 '09 at 16:00
source share

You can use loop.parent inside a nested loop to get the outer loop context

 {% for i in a %} {% for j in i %} {{loop.parent.index}} {% endfor %} {% endfor %} 

This is a much cleaner solution than using temporary variables. Source - http://jinja.pocoo.org/docs/templates/#for

-6
Mar 20 '14 at 2:16
source share



All Articles