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

问题描述:

我的 django 模板中有以下 for 循环显示天数.我想知道,是否可以在循环中迭代一个数字(在下面的情况下 i).还是必须先存到数据库中,然后以days.day_number的形式查询?

I have the following for loop in my django template displaying days. I wonder, whether it's possible to iterate a number (in the below case i) in a loop. Or do I have to store it in the database and then query it in form of days.day_number?

{% for days in days_list %}
    <h2># Day {{ i }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

Django 提供了它.您可以使用:

Django provides it. You can use either:

  • {{ forloop.counter }} 索引从 1 开始.
  • {{ forloop.counter0 }} 索引从 0 开始.
  • {{ forloop.counter }} index starts at 1.
  • {{ forloop.counter0 }} index starts at 0.

在模板中,您可以:

{% for item in item_list %}
    {{ forloop.counter }} # starting index 1
    {{ forloop.counter0 }} # starting index 0

    # do your stuff
{% endfor %}

更多信息:for |内置模板标签和过滤器 |Django 文档