150

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

Tom
  • 42,844
  • 35
  • 95
  • 101
jamesaharvey
  • 14,023
  • 15
  • 52
  • 63

3 Answers3

285

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

Tom
  • 42,844
  • 35
  • 95
  • 101
  • What if I have more than two loops and I want to access certain loop? Should I use "parentloop"."parentloop" to gradully appoarch it? It sounds inefficient. – Alston Apr 28 '23 at 13:55
26

you can also use with

Caches a complex variable under a simpler name. This is useful when accessing an “expensive” method (e.g., one that hits the database) multiple 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 high version of Django you could use

{% with outer_counter=forloop.counter %}

Note: With doesn't allow spaces before or after =

I've checked, Django 1.4.x - Django 1.9.x support the two methods.

this is more clear when have many for loops

MohitC
  • 4,541
  • 2
  • 34
  • 55
WeizhongTu
  • 6,124
  • 4
  • 37
  • 51
0

In some cases the forloop.parentloop is not enough.

Check out django-templateaddons3 and its {% counter %} tag for a full-fledged solution.

AndyTheEntity
  • 3,396
  • 1
  • 22
  • 19