views:

96

answers:

2

I want to travere multiple lists within a django template in the same for loop. How do i do it?

some thinking link this -

{% for item1, item2, item3 in list1, list2 list3 %}

{{ item1 }}, {{ item2 }}, {{ item3 }}

{% endfor %}

Is something like this possible?

+2  A: 

You have two options:

1. You define your objects so that you can access the items like parameters

for x in list:
    {{x.item1}}, {{x.item2}}, {{x.item3}}

Note that you have to make up the list by combining the three lists:

lst = [{'item1': t[0], 'item2': t[1], 'item3':t[2]} for t in zip(list_a, list_b, list_c)]

2. You define your own filter

from django import template

register = template.Library()

@register.filter(name='list_iter')
def list_iter(lists):
    list_a, list_b, list_c = lists

for x, y, z in zip(list_a, list_b, list_c):
    yield (x, y, z)

# test the filter
for x in list_iter((list_a, list_b, list_c)):
    print x

See the filter documentation

the_void
Thanks a ton! perfect solution.
demos
+1  A: 

Abusing django templates:

{% for x in list_a %}
{% with forloop.counter|cut:" " as index %}
  {{ x }},
  {{ list_b|slice:index|last }},
  {{ list_c|slice:index|last }} <br/>
{% endwith %}
{% endfor %}

But NEVER do that!!! just use zip in Your views.

petraszd
Nice hack! :) Might come in handy some day.
demos