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.

可以用以下方法

例如:

{% 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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM