本文介绍了有没有办法在django同时循环两个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个具有相同长度的列表对象,具有补充数据,我想渲染是有一种同时呈现两者的方式。{%for i,j in table,total%}
{{i}}
{ {j}}
{%endfor%}
或类似的东西
解决方案
如果两个列表的长度相同,则可以返回 zipped_data = zip(表,总计)作为您的视图中的模板上下文,它生成2值元组的列表。
示例:
>>> lst1 = ['a','b','c']
>>> lst2 = [1,2,3]
>>> zip(lst1,lst2)
[('a',1),('b',2),('c',3)]
在您的模板中,您可以写:
{%for i,j in zipped_data%}
{{i}},{{j}}
{%endfor%}
另外,请查看Django关于模板标签的的文档。它提到了您使用它的所有可能性,包括很好的例子。
I have two list objects of the same length with complementary data i want to render is there a way to render both at the same time ie.
{% for i,j in table, total %} {{ i }} {{ j }} {% endfor %}
or something similar?
解决方案
If both lists are of the same length, you can return zipped_data = zip(table, total) as template context in your view, which produces a list of 2-valued tuples.
Example:
>>> lst1 = ['a', 'b', 'c'] >>> lst2 = [1, 2, 3] >>> zip(lst1, lst2) [('a', 1), ('b', 2), ('c', 3)]
In your template, you can then write:
{% for i, j in zipped_data %} {{ i }}, {{ j }} {% endfor %}
Also, take a look at Django's documentation about the for template tag here. It mentions all possibilities that you have for using it including nice examples.
这篇关于有没有办法在django同时循环两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!