Abhi Abhi - 1 month ago 9
Python Question

Iterating through two lists in Django templates

I want to do the below list iteration in django templates:

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

for (a, b) in zip(foo, moo):
print a, b


django code:

{%for a, b in zip(foo, moo)%}
{{a}}
{{b}}
{%endfor%}


I get the below error when I try this:

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


How do I accomplish this?

Answer

It's possible to do

{% for ab in mylist %}
    {{ab.0}}
    {{ab.1}}
{% endfor %}

but you cannot make a call to zip within the for structure. You'll have to store the zipped list in another variable first, then iterate over it.

Comments