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