java web开发小记(7)jinjia2中for循环索引

在jinjia2中想直接用

{% for i in n %}
当前是第 x 条
{% endfor %}

是不行的。

{% for i, val in enumerate(['a', 'b', 'c']) %}
    <td>
        {{ val }}
    </td>
{% endfor %}

报错:

UndefinedError: 'enumerate' is undefined

  Jinja2 has its own language. Looks like Python but it's not Python. So the Python enumerate built-in function is not part of Jinja2 template engine.

可以用以下方法

java web开发小记(7)jinjia2中for循环索引

例如:

{% for chose in choses %}
            <li>
                <p>[第{{ loop.index}}题]{{ chose.content }}</p>
                <p>A.{{ chose.a }}</p>
                <p>B.{{ chose.b }}</p>
                <p>C.{{ chose.c }}</p>
                <p>D.{{ chose.d }}</p>
            </li>
        {% endfor %}

  参考:https://segmentfault.com/q/1010000000690359/a-1020000000690397