Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parallel arrays in Django templates?

My view code looks basically like this:

context = Context() 
context['some_values'] = ['a', 'b', 'c', 'd', 'e', 'f']
context['other_values'] = [4, 8, 15, 16, 23, 42]

I would like my template code to look like this:

{% for some in some_values %} 
  {% with index as forloop.counter0 %} 
    {{ some }} : {{ other_values.index }} <br/> 
  {% endwith %} 
{% endfor %} 

And I would expect this to output:

a : 4 <br/> 
b : 8 <br/> 
c : 15 <br/> 
d : 16 <br/> 
e : 23 <br/> 
f : 42 <br/> 

Is this possible? I'm finding that my "with" statement is actually working, but then using that variable as a reference isn't working. I suspect that for {{ other_values.index }} it's doing other_values['index'] instead of other_values[index]. Is this possible?

like image 972
slacy Avatar asked Jan 14 '10 19:01

slacy


1 Answers

zip(some_values, other_values), then use it in template

from itertools import izip
some_values = ['a', 'b', 'c', 'd', 'e', 'f']
other_values = [4, 8, 15, 16, 23, 42]
context['zipped_values'] = izip(some_values, other_values)

{% for some, other in zipped_values %}
    {{ some }}: {{ other }}  <br/>
{% endfor %}
like image 99
Antony Hatchkins Avatar answered Oct 17 '22 12:10

Antony Hatchkins