Django: how to iterate over two lists inside a template
From views.py I am sending an array of templates 2:
- animal:
['cat','dog','mause']
- how_many:
['one','two','three']
Template:
{% for value in animal %}
animal:{{ value }} \ how meny {{ how_many[(forloop.counter0)] }}
{% endfor %}
In the for loop, I want to read the iteration and then use it on the second array, but I cannot get it to work. I am newbie.
As per the docs, you can't do it in a straight forward way :
Note that "bar" in a template expression such as {{foo.bar}} will be interpreted as a literal string and will not use the value of the variable "bar" if it exists in the template context.
I would suggest you add zip(animal, how_many)
to your template context:
context['animals_data'] = zip(animal, how_many)
Then you can access both lists:
{% for animal, how_many in animals_data %}
{{ animal }} {{ how_many }}
{% endfor %}
I would recommend writing your own template tag for this problem. Place the following (from this SO question ) in a template called an index to be stored in templatetags/index.py
:
from django import template
register = template.Library()
@register.filter
def index(List, i):
return List[int(i)]
Now, downloading this and using it should be simple:
{% load index %}
{% for value in animal %}
animal:{{ value }} \ how meny {{ how_meny|index:forloop.counter0 }}
{% endfor %}
Try the following:
animal = ['cat','dog','mause']
how_many = ['one','two','three']
data = zip(animal,how_many)
return render_to_response('your template', {'data': data})
In the template
{% for i,j in data %}
{{i}} {{j}}
{% endfor %}