Python 如何使用jijna2获取for循环的当前索引?

Python 如何使用jijna2获取for循环的当前索引?,python,jinja2,Python,Jinja2,假设我有这样一个代码: {% for x in posts %} <p>We are in item: {{ x }}</> {% else %} {%x在posts%} 我们在项目中:{x} {%else%} 我想得到for循环的当前索引以运行if循环,类似于(逻辑上): {%x在posts%} {%x.index=0%} 我们在第一项中 {%else%} 我们在项目中:{x} {%endif%} {%endfor%} 如何在jijna2内完成?(我在Fla

假设我有这样一个代码:

{% for x in posts %}
   <p>We are in item: {{ x }}</>
{% else %}
{%x在posts%}
我们在项目中:{x}
{%else%}
我想得到for循环的当前索引以运行if循环,类似于(逻辑上):

{%x在posts%}
{%x.index=0%}
我们在第一项中

{%else%} 我们在项目中:{x} {%endif%} {%endfor%}

如何在jijna2内完成?(我在Flask中使用Python)。

您可以在循环中使用
loop.index

{% for x in posts %}
    <p>We are in item number: {{ loop.index }}</>
{% else %}
{%x在posts%}
我们在项目编号中:{{loop.index}
{%else%}

您可以使用几个与循环相关的变量

{% for x in posts %}
    <p>We are in item number: {{ loop.index }}</>
{% else %}