如何用jinja2获取for循环的当前索引?
How to get the current index of for loop with jijna2?
假设我有这样的代码:
{% for x in posts %}
<p>We are in item: {{ x }}</>
{% else %}
我想将 for 循环的当前索引获取到 运行 一个 if 循环,类似于(逻辑上):
{% for x in posts %}
{% if x.index = 0 %}
<p>We are in the first item!</p>
{% else %}
<p>We are in item: {{ x }}</>
{% endif %}
{% endfor %}
如何在jijna2里面做? (我在 Flask 中使用 Python)。
您可以在循环中使用 loop.index
。
{% for x in posts %}
<p>We are in item number: {{ loop.index }}</>
{% else %}
您可以为此使用多个与循环相关的变量
http://jinja.pocoo.org/docs/dev/templates/#list-of-control-structures
假设我有这样的代码:
{% for x in posts %}
<p>We are in item: {{ x }}</>
{% else %}
我想将 for 循环的当前索引获取到 运行 一个 if 循环,类似于(逻辑上):
{% for x in posts %}
{% if x.index = 0 %}
<p>We are in the first item!</p>
{% else %}
<p>We are in item: {{ x }}</>
{% endif %}
{% endfor %}
如何在jijna2里面做? (我在 Flask 中使用 Python)。
您可以在循环中使用 loop.index
。
{% for x in posts %}
<p>We are in item number: {{ loop.index }}</>
{% else %}
您可以为此使用多个与循环相关的变量
http://jinja.pocoo.org/docs/dev/templates/#list-of-control-structures