Iterating through two lists in Django templates
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.
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%}
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.