Django模板:遍历两个列表 [英] Django Template: looping through two lists

查看:534
本文介绍了Django模板:遍历两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个Django模型对象列表,我想在模板上显示它们。 list1 是一维数组,而 list1 是二维数组。在模板中,我想遍历 list1 中的每个元素,显示其值,然后显示 list2 <中的相应元素的所有值/ code>。

I have two lists of Django model objects, which I want to display on a template. list1 is a one-dimensional array, and list1 is a two-dimensional array. In the template, I want to loop through each element in list1, display its value, and then display all the values of the corresponding element in list2.

例如,如果 list1 = ['Andrew','Ben,'Charles'] list2 = [[3,4,8],[12,9],[10,0,5,1]] ,那么我想显示:

For example, if list1 = ['Andrew', 'Ben,' 'Charles'] and list2 = [[3, 4, 8], [12, 9], [10, 0, 5, 1]], then I want to display:

- Andrew
    - 3
    - 4
    - 8
- Ben
    - 12
    - 9
- Charles
    - 10
    - 0
    - 5
    - 1

我的问题是,在我的模板中,如何循环遍历 list1 然后访问 list2 的相应元素?以下代码是我到目前为止所拥有的:

My question is, in my template, how can I loop through list1 and then access the corresponding element of list2? The following code is what I have so far:

<ul>
    {% for name in list1 %}
    <li>{{ name }}
        <ul>
            {% for A %}
            <li>{{ B }}</li>
            {% endfor %}
        </ul>    
    </li>
    {% endfor %}
</ul>

我应该用什么代替 A B

推荐答案

在python视图中,您可以将它们压缩在一起。

In the python view you can zip them together.

def someview(request):
    list1 = ['Andrew', 'Ben,' 'Charles']
    list2 = [[3, 4, 8], [12, 9], [10, 0, 5, 1]]
    zipped_list = zip(list1, list2)
    return render(request, 'base/home.html', {'zipped_list': zipped_list})



base / home.html



base/home.html

<ul>
    {% for item1 in zipped_list %} <- this is now a tuple with the first element being our first item and the second element being a list
    <li>{{ item1.0 }}
        <ul>
            {% for secondItem in item1.1 %}
                <li>{{ secondItem }}</li>
            {% endfor %}
        </ul>    
    </li>
    {% endfor %}
</ul>

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

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