我的 django 模板中有以下 for 循环显示天数。我想知道,是否有可能在循环中迭代一个数字(在下面的例子中是 i)。还是必须先存入数据库,然后再以days.day_number的形式查询?
{% for days in days_list %}
<h2># Day {{ i }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
最佳答案
Django 提供了它。您可以使用:
{{ forloop.counter }}
索引从 1 开始。{{ forloop.counter0 }}
索引从 0 开始。
在模板中,您可以:
{% for item in item_list %}
{{ forloop.counter }} # starting index 1
{{ forloop.counter0 }} # starting index 0
# do your stuff
{% endfor %}
更多信息请访问:for | Built-in template tags and filters | Django documentation
关于Django - 在模板的for循环中迭代数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11481499/