Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to iterate over two lists inside template [duplicate]

Tags:

python

django

From views.py I send to template 2 array:

  1. animal: ['cat','dog','mause']
  2. 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 an iteration and then use it in a second array, but I can't get it to work. I'm a beginner.

like image 203
Damian184 Avatar asked Dec 25 '22 16:12

Damian184


2 Answers

According to the docs, you can't do that straightforward:

Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context.

I would suggest you to add zip(animal, how_many) to your template's 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 %}
like image 55
Ernest Ten Avatar answered Feb 06 '23 19:02

Ernest Ten


Try this:

animal = ['cat','dog','mause']
how_many = ['one','two','three']
data = zip(animal,how_many)
return render_to_response('your template', {'data': data})

In Template

{% for i,j in data %}
{{i}}   {{j}}
{% endfor %}
like image 33
chandu Avatar answered Feb 06 '23 19:02

chandu