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

时间:2022-09-18 14:31:25

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?

我在django模板中有如下的for循环显示天数。我想知道,是否可以在循环中迭代一个数字(在下面的例子I中)。或者我必须将它存储在数据库中,然后以day .day_number的形式查询它吗?

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

2 个解决方案

#1


347  

Django provides it you can use {{ forloop.counter }} index start at 1 or {{ forloop.counter0 }} index start at 0.

Django提供它可以使用{{forloop}。计数器}索引从1或{{forloop}开始。}索引从0开始。

More info at Django template forloop

更多信息请访问Django模板forloop

Just to add quick help here rather than going to django doc.

在这里添加快速帮助,而不是去django doc。

In template you can do

在模板中你可以这样做

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

    {# do your stuff #}
{% endfor %}

#2


18  

Also one can use this:

你也可以用这个:

{% if forloop.first %}

or

{% if forloop.last %}

#1


347  

Django provides it you can use {{ forloop.counter }} index start at 1 or {{ forloop.counter0 }} index start at 0.

Django提供它可以使用{{forloop}。计数器}索引从1或{{forloop}开始。}索引从0开始。

More info at Django template forloop

更多信息请访问Django模板forloop

Just to add quick help here rather than going to django doc.

在这里添加快速帮助,而不是去django doc。

In template you can do

在模板中你可以这样做

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

    {# do your stuff #}
{% endfor %}

#2


18  

Also one can use this:

你也可以用这个:

{% if forloop.first %}

or

{% if forloop.last %}