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
<
You can use zip
in your view:
mylist = zip(list1, list2)
context = {
'mylist': mylist,
}
return render(request, 'template.html', context)
and in your template use
{% for item1, item2 in mylist %}
to iterate through both lists.
This should work with all version of Django.
You can make the foo objects properties of the moo objects on the server side.
for f, b in zip(foo, bar):
f.foosBar = b
context = {
"foo": foo
}
This is especially clean when the second list are properties of the first (which is typically the case).
users = User.objects.all()
for user in users:
user.bestFriend = findBestFriendForUser(user)
context = {
"users": users
}
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.
Simply define zip as a template filter:
@register.filter(name='zip')
def zip_lists(a, b):
return zip(a, b)
Then, in your template:
{%for a, b in first_list|zip:second_list %}
{{a}}
{{b}}
{%endfor%}
In views.py:
foo = ['foo', 'bar']
moo = ['moo', 'loo']
zipped_list = zip(foo,moo)
return render(request,"template.html",{"context":zipped_list}
In template.html:
{% for f,m in context%}
{{f}}{{m}}
{% endfor %}
If f
is a queryset returned from database then access it by {{f.required_attribute_name}}
I built django-multiforloop to solve this problem. From the README:
With django-multiforloop installed, rendering this template
{% for x in x_list; y in y_list %}
{{ x }}:{{ y }}
{% endfor %}
with this context
context = {
"x_list": ('one', 1, 'carrot'),
"y_list": ('two', 2, 'orange')
}
will output
one:two
1:2
carrot:orange