在同一for循环中遍历Django模板中的多个列表 [英] Traversing multiple lists in django template in same for loop

查看:40
本文介绍了在同一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

请参见过滤器文档

这篇关于在同一for循环中遍历Django模板中的多个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆