How to access external forloop.counter file with nested loops in Django templates?

Is it possible to access forloop.counter for the outer 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 the loop counter in the above example

+84
django django-templates
Mar 04
source share
2 answers

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

+157
Mar 04 '10 at 2:39
source share

you can also use with

Caches a complex variable under a simpler name. This is useful when accessing an β€œexpensive” method (for example, one that gets into the database) several times.

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

if using a high version of django you can use

 {% with outer_counter = forloop.counter %} 

I checked Django 1.4.x - Django 1.9.x supports two methods.

this is more understandable when they have many cycles

+6
Jun 29 '16 at 8:56
source share



All Articles