Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
Abhi Avatar asked Mar 10 '10 09:03

Abhi


People also ask

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

How do I loop a model in Django?

To iterate over model instance field names and values in template with Django Python, we can use a queryset serializer. to serialize the queryset results with serializers. serialize . to loop through the data list and get the values from instance.


2 Answers

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.

like image 117
Mermoz Avatar answered Oct 17 '22 16:10

Mermoz


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%} 
like image 32
Marco Avatar answered Oct 17 '22 16:10

Marco