Abhi Abhi - 1 year ago 110
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)%}

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 Source

It's possible to do

{% for ab in mylist %}
{% 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download