104

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?

3 Answers 3

182

Store it in a variable, for example:

{% for i in a %}
    {% set outer_loop = loop %}
    {% for j in a %}
        {{ outer_loop.index }}
    {% endfor %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

3 Comments

Just note that the index will start from 1 and not 0.
Also note loop.index0 would let you access index starting from 0 (jinja.pocoo.org/docs/dev/templates/#for)
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?
1

@senaps I just changed outer_loop.index to index0 this returns the iteration with a 0 index. So the first item starts with a 0

{% for i in a %}
    {% set outer_loop = loop %}
    {% for j in a %}
        {{ outer_loop.index0 }}
    {% endfor %}
{% endfor %}

1 Comment

Welcome to StackOverflow. Please, edit and try for How to Answer, describe the effect of what you propose and explain why it helps to solve the problem, make the additional insight more obvious which you contribute beyond existing answers, the relevant advantage which your solution achieves, especially if the difference is so small and non-obvious. Consider taking the tour.
-13

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

2 Comments

Perhaps @KannanGanesan was thinking of twig.

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.