How to access outermost forloop.counter with nested for loops in Django templates?

jamesaharvey picture jamesaharvey · Mar 4, 2010 · Viewed 33.5k times · Source

Is it possible to access the forloop.counter for the outermost for loop in the following template in Django:

{% for outerItem in outerItems %}
    {% for item in items%}
        <div>{{ forloop.counter }}.&nbsp;{{ item }}</div>
    {% endfor %}
{% endfor %}

forloop.counter returns the innermost for loop's counter in the above example

Answer

Tom picture Tom · Mar 4, 2010

You can use forloop.parentloop to get to the outer forloop, so in your case {{forloop.parentloop.counter}}.