views:

140

answers:

1

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?

+4  A: 

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 %}
Antony Hatchkins
I'd use `itertools.izip` instead.
PiotrLegnica
slacy
@slacy: Your question is not purely about presentation. The association between items is essential in two "parallel" arrays. "Parallel" arrays are really just 2-tuples waiting to be created. You *should* put them together in the view function because they absolutely belong together logically. That's why you're presenting them together.
S.Lott
@PiotrLegnica: absolutely. Fixed. Also with izip it wont create a huge new structure in memory.
Antony Hatchkins