Django计数器循环到索引列表 [英] Django counter in loop to index list

查看:382
本文介绍了Django计数器循环到索引列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将两个列表传递给一个模板。通常,如果我在列表中迭代,我会做这样的事情

  {%for i in list%} 

但是我有两个需要并行访问的列表,即。一个列表中的第n个项目对应于另一个列表中的第n个项目。我的想法是循环使用一个列表,并使用forloop.counter0访问另一个列表中的一个项目,但是我无法弄清楚语法是否正常工作。



谢谢

解决方案

你不能。简单的方法是在压缩列表中预处理数据,像这样



在您的视图中

  x = [1,2,3] 
y = [4,5,6]
zipped = zip(x,y)

然后在你的模板中:

  {%for x,y in zipped%} 
{{x}} - {{y}}
{%endfor%}


I'm passing two lists to a template. Normally if I was iterating over a list I would do something like this

{% for i in list %}

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list. My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks

解决方案

You can't. The simple way is to preprocess you data in a zipped list, like this

In your view

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)

Then in you template :

{% for x, y in zipped %}
    {{ x }} - {{ y }}
{% endfor %}

这篇关于Django计数器循环到索引列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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