Is it possible to access the forloop.counter for the outermost for loop in the following template in Django:
可以访问forloop吗?下面Django模板中最外层for循环的计数器:
{% for outerItem in outerItems %}
{% for item in items%}
<div>{{ forloop.counter }}. {{ item }}</div>
{% endfor %}
{% endfor %}
forloop.counter returns the innermost for loop's counter in the above example
forloop。计数器在上面的例子中返回循环计数器的最里面。
2 个解决方案
#1
173
You can use forloop.parentloop
to get to the outer forloop
, so in your case {{forloop.parentloop.counter}}
.
您可以使用forloop。为了到达外部的forloop,所以在您的例子{forloop.parentloop.counter}中。
#2
7
you can also use with
你也可以用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 }}. {{ item }}</div>
{% endfor %}
{% endwith %}
{% endfor %}
if using high version of Django you could use
如果使用高版本的Django,您可以使用。
{% with outer_counter = forloop.counter %}
I've checked, Django 1.4.x - Django 1.9.x support the two methods.
我已经检查,Django 1.4。1.9 x - Django。x支持这两种方法。
this is more clear when have many for loops
当有许多for循环时,这就更清晰了
#1
173
You can use forloop.parentloop
to get to the outer forloop
, so in your case {{forloop.parentloop.counter}}
.
您可以使用forloop。为了到达外部的forloop,所以在您的例子{forloop.parentloop.counter}中。
#2
7
you can also use with
你也可以用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 }}. {{ item }}</div>
{% endfor %}
{% endwith %}
{% endfor %}
if using high version of Django you could use
如果使用高版本的Django,您可以使用。
{% with outer_counter = forloop.counter %}
I've checked, Django 1.4.x - Django 1.9.x support the two methods.
我已经检查,Django 1.4。1.9 x - Django。x支持这两种方法。
this is more clear when have many for loops
当有许多for循环时,这就更清晰了