Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 334
jamesaharvey Avatar asked Mar 04 '10 02:03

jamesaharvey


People also ask

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

How do you exit a loop in Django?

There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.) 1- Use with to define a variable to determine current status, 2- Use a template custom tag to change statement to negate current status.


1 Answers

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

like image 111
Tom Avatar answered Oct 01 '22 18:10

Tom