如何在Django模板中使用嵌套for循环访问最外层的forloop.counter?

jam*_*vey 109 django django-templates

是否可以在Django的以下模板中访问最外层for循环的forloop.counter:

{% for outerItem in outerItems %}
    {% for item in items%}
        <div>{{ forloop.counter }}.&nbsp;{{ item }}</div>
    {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,forloop.counter返回最里面的for循环计数器

Tom*_*Tom 212

你可以用forloop.parentloop来到外面forloop,所以在你的情况下{{forloop.parentloop.counter}}.

  • 仅供参考 - {{forloop.parentloop.parentloop.counter}}也有效 (30认同)

Wei*_*gTu 12

你也可以使用

以更简单的名称缓存复杂变量.这在多次访问"昂贵"方法(例如,击中数据库的方法)时很有用.

{% for outerItem in outerItems %}
  {% with forloop.counter as outer_counter %}
    {% for item in items%}
        <div>{{ outer_counter }}.&nbsp;{{ item }}</div>
    {% endfor %}
  {% endwith %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

如果使用高版本的Django你可以使用

{% with outer_counter = forloop.counter %}
Run Code Online (Sandbox Code Playgroud)

我查了一下,Django 1.4.x - Django 1.9.x支持这两种方法.

当有许多for循环时,这个更清楚