我将两个列表传递给模板.通常,如果我在列表上进行迭代,我会做这样的事情
{% for i in list %}
Run Code Online (Sandbox Code Playgroud)
但我有两个需要并行访问的列表,即.一个列表中的第n个项目对应于另一个列表中的第n个项目.我的想法是循环遍历一个列表并使用forloop.counter0访问另一个列表中的项目,但我无法弄清楚要使其工作的语法.
谢谢
Xav*_*osa 16
你不能.简单的方法是在压缩列表中预处理数据,就像这样
在你看来
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中:
{% for x, y in zipped %}
{{ x }} - {{ y }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
Cau*_*ons 12
要使用forloop计数器访问iterable,我编写了以下非常简单的过滤器:
from django import template
register = template.Library()
@register.filter
def index(sequence, position):
return sequence[position]
Run Code Online (Sandbox Code Playgroud)
然后我可以在我的模板中使用它(不要忘记加载它):
{% for item in iterable1 %}
{{ iterable2|index:forloop.counter0 }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
希望这有助于其他人!
听起来你正在寻找我的django-multiforloop.来自README:
渲染此模板
{% load multifor %}
{% for x in x_list; y in y_list %}
{{ x }}:{{ y }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
有了这个背景
context = {
"x_list": ('one', 1, 'carrot'),
"y_list": ('two', 2, 'orange')
}
Run Code Online (Sandbox Code Playgroud)
将输出
one:two
1:2
carrot:orange
Run Code Online (Sandbox Code Playgroud)
小智 6
我最终不得不这样做:
{% for x in x_list %}
{% for y in y_list %}
{% if forloop.counter == forloop.parentloop.counter %}
Do Something
{% endif %}
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12119 次 |
| 最近记录: |