Django - 在模板的for循环中迭代数字

标签 django for-loop django-templates

我的 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/

相关文章:

python - 脚本在读取文件时跳过第二个 for 循环

Django 表单向导 - 每个步骤的自定义表单布局

Python 和 sqlite3 - 导入和导出数据库

Django + Docker + SQLite3 如何将数据库挂载到容器中?

django - 我可以让 Django 管理员反射(reflect)模型的层次结构吗?

python - 如何在我的模板中给出小数点后两位?

django - 使用主键 django {% url %} 重定向

Django-extension runscript 脚本没有(有效)模块

python - 在 Python 中编写这个 for 循环的最优雅的方法是什么?

循环中的 R 条件格式