在同一for循环中遍历Django模板中的多个列表

问题描述:

我想遍历同一for循环中django模板中的多个列表.我该怎么办?

I want to traverse multiple lists within a django template in the same for loop. How do i do it?

一些思维链接:

{% for item1, item2, item3 in list1, list2 list3 %}

{{ item1 }}, {{ item2 }}, {{ item3 }}

{% endfor %}

这样可能吗?

您有两个选择:

1.您定义对象,以便可以访问诸如参数之类的项目

for x in list:
    {{x.item1}}, {{x.item2}}, {{x.item3}}

请注意,您必须通过合并三个列表来构成列表:

Note that you have to make up the list by combining the three lists:

lst = [{'item1': t[0], 'item2': t[1], 'item3':t[2]} for t in zip(list_a, list_b, list_c)]

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

请参见过滤器文档