Manish Gupta
Manish Gupta

Reputation: 4656

multiple for loop in django template

In django the syntax for using a for loop over a list or array is:

{% for each in list %}
    <td>{{ each }}</td>
{% endfor %}

if i use nested loop then the data span over multiple columns.

How to iterate over two or more lists at same time. I have 5 lists i want to iterate over.

e.g in python i can use something like:

for x,y in zip(ls1, ls2):
    #Do your work

Upvotes: 0

Views: 6559

Answers (2)

Ruben Aguilar
Ruben Aguilar

Reputation: 1235

You can zip the two lists before render the template, and pass the zip as parameter:

zippedList = zip(list1, list2)
return render('template.html', {'list': zippedList})

And in the template:

{% for item1, item2 in list %}

This way you can iterate over the two lists.

Upvotes: 0

juree
juree

Reputation: 273

Use foo = zip(list1,list2,list3,...) inside your view, then iterate in template:

{% for a,b,c,d,e in list %}
    ....
{% endfor %}

Another option is to write your custom {% for %} template tag.

Btw: Using list as variable is not good practice because you override list() function

Upvotes: 4

Related Questions