4

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.

frlan
  • 6,950
  • 3
  • 31
  • 72
Damian184
  • 41
  • 1
  • 4

3 Answers3

8

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 %}
Ernest
  • 2,799
  • 12
  • 28
2

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 %}
chandu
  • 1,053
  • 9
  • 18
1

I would recommend writing your own template tag for this problem. Put the following (from this SO question) in a template called index which should be saved in templatetags/index.py:

from django import template
register = template.Library()

@register.filter
def index(List, i):
    return List[int(i)]

Now, loading this and using it should be as simple as:

{% load index %}
{% for value in animal %}
  animal:{{ value }}  \ how meny {{ how_meny|index:forloop.counter0 }}
{% endfor %}
Community
  • 1
  • 1
GJStein
  • 648
  • 5
  • 13