94

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

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

Anto
  • 6,806
  • 8
  • 43
  • 65
flybywire
  • 261,858
  • 191
  • 397
  • 503

2 Answers2

162

Store it in a variable, for example:

{% for i in a %}
    {% set outer_loop = loop %}
    {% for j in a %}
        {{ outer_loop.index }}
    {% endfor %}
{% endfor %}
Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
  • 4
    Just note that the index will start from 1 and not 0. – scottydelta Jul 13 '15 at 17:21
  • 5
    Also note loop.index0 would let you access index starting from 0 (http://jinja.pocoo.org/docs/dev/templates/#for) – Scott Yang Aug 22 '15 at 23:16
  • 1
    what if we wanted to show the loop index as row number in a table? this code here isn't considering that and inner loop will be shown as 1 untill it ends. how we handle that? – senaps Sep 12 '17 at 04:50
-12

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

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

  • 11
    This is wrong. Jinja doesn't support .parent. See http://jinja.pocoo.org/docs/tricks/#accessing-the-parent-loop and http://jinja.pocoo.org/docs/templates/#for. – Romz Apr 13 '14 at 16:18
  • 1
    Perhaps @KannanGanesan was thinking of [twig](https://stackoverflow.com/a/18734849/328817). – Sam Mar 19 '19 at 09:28