小编典典

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

django

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

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

阅读 632

收藏
2020-03-27

共1个答案

小编典典

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 %}
2020-03-27