如何在python jinja模板中输出loop.counter? [英] How to output loop.counter in python jinja template?
本文介绍了如何在python jinja模板中输出loop.counter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够将当前循环迭代输出到我的模板.
I want to be able to output the current loop iteration to my template.
根据文档: http://wsgiarea.pocoo.org/jinja/docs /loops.html ,我正在尝试使用一个loop.counter变量.
According to the docs: http://wsgiarea.pocoo.org/jinja/docs/loops.html, there is a loop.counter variable that I am trying to use.
我有以下内容:
<ul>
{% for user in userlist %}
<li>
{{ user }} {{loop.counter}}
</li>
{% if loop.counter == 1 %}
This is the First user
{% endif %}
{% endfor %}
</ul>
尽管没有任何输出到我的模板.正确的语法是什么?
Though nothing is being output to my template. What is the correct syntax?
推荐答案
循环的计数器变量在jinja2中称为 loop.index .
The counter variable inside the loop is called loop.index in jinja2.
>>> from jinja2 import Template
>>> s = "{% for element in elements %}{{loop.index}} {% endfor %}"
>>> Template(s).render(elements=["a", "b", "c", "d"])
1 2 3 4
有关更多信息,请参见 http://jinja.pocoo.org/docs/templates/
See http://jinja.pocoo.org/docs/templates/ for more.
这篇关于如何在python jinja模板中输出loop.counter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文