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

孤街醉人 提交于 2019-12-17 15:37:25

问题


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


回答1:


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




回答2:


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 %}

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

this is more clear when have many for loops



来源:https://stackoverflow.com/questions/2376511/how-to-access-outermost-forloop-counter-with-nested-for-loops-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!