django模板中的多个for循环
multiple for loop in django template
在 django 中,在列表或数组上使用 for 循环的语法是:
{% for each in list %}
<td>{{ each }}</td>
{% endfor %}
如果我使用嵌套循环,那么数据会跨越多个列。
如何同时遍历两个或多个列表。我有 5 个列表要迭代。
例如 python 我可以使用类似的东西:
for x,y in zip(ls1, ls2):
#Do your work
在您的视图中使用 foo = zip(list1,list2,list3,...)
,然后在模板中迭代:
{% for a,b,c,d,e in list %}
....
{% endfor %}
另一种选择是编写自定义 {% for %} 模板标签。
顺便说一句:使用 list
作为变量不是好的做法,因为您覆盖了 list()
函数
您可以在呈现模板之前压缩两个列表,并将压缩作为参数传递:
zippedList = zip(list1, list2)
return render('template.html', {'list': zippedList})
并且在模板中:
{% for item1, item2 in list %}
这样你就可以遍历两个列表。
在 django 中,在列表或数组上使用 for 循环的语法是:
{% for each in list %}
<td>{{ each }}</td>
{% endfor %}
如果我使用嵌套循环,那么数据会跨越多个列。
如何同时遍历两个或多个列表。我有 5 个列表要迭代。
例如 python 我可以使用类似的东西:
for x,y in zip(ls1, ls2):
#Do your work
在您的视图中使用 foo = zip(list1,list2,list3,...)
,然后在模板中迭代:
{% for a,b,c,d,e in list %}
....
{% endfor %}
另一种选择是编写自定义 {% for %} 模板标签。
顺便说一句:使用 list
作为变量不是好的做法,因为您覆盖了 list()
函数
您可以在呈现模板之前压缩两个列表,并将压缩作为参数传递:
zippedList = zip(list1, list2)
return render('template.html', {'list': zippedList})
并且在模板中:
{% for item1, item2 in list %}
这样你就可以遍历两个列表。