迭代Django模板中的两个列表

Abh*_*bhi 33 python django django-templates

我想在django模板中进行以下列表迭代:

foo = ['foo', 'bar'];
moo = ['moo', 'loo'];

for (a, b) in zip(foo, moo):
    print a, b
Run Code Online (Sandbox Code Playgroud)

django代码:

{%for a, b in zip(foo, moo)%}
  {{a}}
  {{b}}
{%endfor%}
Run Code Online (Sandbox Code Playgroud)

我尝试这个时收到以下错误:

File "/base/python_lib/versions/third_party/django-0.96/django/template/defaulttags.py", line 538, in do_for
    raise TemplateSyntaxError, "'for' statements should have either four or five words: %s" % token.contents
Run Code Online (Sandbox Code Playgroud)

我该如何做到这一点?

Mer*_*moz 62

您可以zip在视图中使用:

mylist = zip(list1, list2)
context = {
            'mylist': mylist,
        }
return render(request, 'template.html', context)
Run Code Online (Sandbox Code Playgroud)

并在您的模板中使用

{% for item1, item2 in mylist %}
Run Code Online (Sandbox Code Playgroud)

迭代两个列表.

这适用于所有版本的Django.

  • 不要使用"list"作为变量名,因为这会破坏内置的. (3认同)

Mar*_*rco 31

只需将zip定义为模板过滤器:

@register.filter(name='zip')
def zip_lists(a, b):
  return zip(a, b)
Run Code Online (Sandbox Code Playgroud)

然后,在您的模板中:

{%for a, b in first_list|zip:second_list %}
  {{a}}
  {{b}}
{%endfor%}
Run Code Online (Sandbox Code Playgroud)


Joh*_*rra 20

这是可能的

{% for ab in mylist %}
    {{ab.0}}
    {{ab.1}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

但你不能zipfor结构内打电话.您必须先将压缩列表存储在另一个变量中,然后迭代它.


Gab*_*ant 8

我建立了django-multiforloop来解决这个问题.来自README:

安装django-multiforloop后,渲染此模板

{% 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)