我希望能够将当前循环迭代输出到我的模板。

根据文件,有个循环。计数器变量,我试图使用:

<ul>
{% for user in userlist %}
  <li>
      {{ user }} {{loop.counter}}
  </li>
      {% if loop.counter == 1 %}
          This is the First user
      {% endif %}
{% endfor %}
</ul>

而是被输出到我的模板中。正确的语法是什么?


循环内部的计数器变量称为循环。Jinja2索引。

>>> from jinja2 import Template

>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4

除了循环。指数,也有

循环。Index0(从0开始的索引) 循环。Revindex(反向索引;结束于1) 循环。Revindex0(反向索引;结束于0) 更多信息请访问http://jinja.pocoo.org/docs/templates/。


在for-loop块内部,您可以访问一些特殊的变量,例如loop。索引(但不是loop.counter)。官方文件显示:

Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if first iteration.
loop.last True if last iteration.
loop.length The number of items in the sequence.
loop.cycle A helper function to cycle between a list of sequences.
loop.depth Indicates how deep in a recursive loop the rendering currently is. Starts at level 1
loop.depth0 Indicates how deep in a recursive loop the rendering currently is. Starts at level 0
loop.previtem The item from the previous iteration of the loop. Undefined during the first iteration.
loop.nextitem The item from the following iteration of the loop. Undefined during the last iteration.
loop.changed(*val) True if previously called with a different value (or not called at all).

如果你正在使用Django,请使用forloop。用Counter代替loop.counter:

<ul>
{% for user in userlist %}
  <li>
      {{ user }} {{forloop.counter}}
  </li>
      {% if forloop.counter == 1 %}
          This is the First user
      {% endif %}
{% endfor %}
</ul>

在Python代码中:

env = Environment(loader=FileSystemLoader("templates"))
env.globals["enumerate"] = enumerate

在模板中:

{% for idx, val in enumerate(list) %}
    {{ idx }}. {{val}}
{% endfor %}

现实生活中的例子:

{% for image in item['images'] %}
    {% set image_id = item_id ~ '-preview-' ~ loop.index0 %}
    <div id="{{ image_id }}" class="overlay">
        <a class="cancel" href="#{{ item_id }}"></a>
        <div class="popup">
            {% set src = image if image.startswith('http') else '/static/images/store/' ~ item_id ~ '/' ~ image %}
            <a href="{{ src }}"><img class="modal-img" src="{{ src }}"/></a>
        </div>
    </div>
{% endfor %}