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

Mad*_*dno 3 python jinja2

假设我有一个类似的代码:

{% for x in posts %}
   <p>We are in item: {{ x }}</>
{% else %}
Run Code Online (Sandbox Code Playgroud)

我想获取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 %}
Run Code Online (Sandbox Code Playgroud)

在jijna2里面怎么做?(我在Flask中使用Python)。

ssu*_*raj 5

您可以loop.index在循环内使用。

{% for x in posts %}
    <p>We are in item number: {{ loop.index }}</>
{% else %}
Run Code Online (Sandbox Code Playgroud)

烧瓶模板文档