dem*_*mos 11 django list django-templates
我想在同一个for循环中遍历django模板中的多个列表.我该怎么做?
一些思考链接:
{% for item1, item2, item3 in list1, list2 list3 %}
{{ item1 }}, {{ item2 }}, {{ item3 }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
这样的事情可能吗?
the*_*oid 22
您有两种选择:
1.定义对象,以便可以访问参数等项目
for x in list:
{{x.item1}}, {{x.item2}}, {{x.item3}}
Run Code Online (Sandbox Code Playgroud)
请注意,您必须通过组合三个列表来组成列表:
lst = [{'item1': t[0], 'item2': t[1], 'item3':t[2]} for t in zip(list_a, list_b, list_c)]
Run Code Online (Sandbox Code Playgroud)
2.您定义自己的过滤器
from django import template
register = template.Library()
@register.filter(name='list_iter')
def list_iter(lists):
list_a, list_b, list_c = lists
for x, y, z in zip(list_a, list_b, list_c):
yield (x, y, z)
# test the filter
for x in list_iter((list_a, list_b, list_c)):
print x
Run Code Online (Sandbox Code Playgroud)
请参阅过滤器文档
滥用django模板:
{% for x in list_a %}
{% with forloop.counter|cut:" " as index %}
{{ x }},
{{ list_b|slice:index|last }},
{{ list_c|slice:index|last }} <br/>
{% endwith %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
但绝不要那样做!只需在您的视图中使用zip.