我有以下for循环在我的django模板显示天数。我想知道,是否有可能在循环中迭代一个数字(在下面的情况下I)。或者我必须把它存储在数据库中,然后以days.day_number的形式查询它?
{% for days in days_list %}
<h2># Day {{ i }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
我有以下for循环在我的django模板显示天数。我想知道,是否有可能在循环中迭代一个数字(在下面的情况下I)。或者我必须把它存储在数据库中,然后以days.day_number的形式查询它?
{% for days in days_list %}
<h2># Day {{ i }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
当前回答
{% for days in days_list %}
<h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
或者你想从0开始
{% for days in days_list %}
<h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
其他回答
我认为你可以调用id,像这样
{% for days in days_list %}
<h2># Day {{ days.id }} - 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 %}
更多信息在:|内置模板标签和过滤器| Django文档
你也可以用这个:
{% if forloop.first %}
or
{% if forloop.last %}
[Django HTML模板现在不支持索引],但是你可以达到这个目标:
如果在views.py中使用Dictionary内部Dictionary,则可以使用key作为索引进行迭代。例子:
{% for key, value in DictionartResult.items %} <!-- dictionartResult is a dictionary having key value pair-->
<tr align="center">
<td bgcolor="Blue"><a href={{value.ProjectName}}><b>{{value.ProjectName}}</b></a></td>
<td> {{ value.atIndex0 }} </td> <!-- atIndex0 is a key which will have its value , you can treat this key as index to resolve-->
<td> {{ value.atIndex4 }} </td>
<td> {{ value.atIndex2 }} </td>
</tr>
{% endfor %}
如果在字典中使用List,那么不仅可以控制第一次和最后一次迭代,而且可以控制所有索引。例子:
{% for key, value in DictionaryResult.items %}
<tr align="center">
{% for project_data in value %}
{% if forloop.counter <= 13 %} <!-- Here you can control the iteration-->
{% if forloop.first %}
<td bgcolor="Blue"><a href={{project_data}}><b> {{ project_data }} </b></a></td> <!-- it will always refer to project_data[0]-->
{% else %}
<td> {{ project_data }} </td> <!-- it will refer to all items in project_data[] except at index [0]-->
{% endif %}
{% endif %}
{% endfor %}
</tr>
{% endfor %}
结束If;)
// 希望已经覆盖的解决方案与字典,列表,HTML模板,循环,内部循环,如果Else。 Django HTML Documentaion更多方法:https://docs.djangoproject.com/en/2.2/ref/templates/builtins/
{% for days in days_list %}
<h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}
或者你想从0开始
{% for days in days_list %}
<h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}