如何在Django模板中访问平行数组?

6 投票
1 回答
789 浏览
提问于 2025-04-15 18:02

我的视图代码大致是这样的:

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

我希望我的模板代码看起来像这样:

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

我预计输出会是:

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

这可能吗?我发现我的“with”语句实际上是有效的,但在使用那个变量作为引用时却不行。我怀疑对于 {{ other_values.index }},它实际上是在做 other_values['index'] 而不是 other_values[index]。这可能吗?

1 个回答

8

some_valuesother_values这两个值用zip函数合并在一起,然后在模板中使用它。

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 %}

撰写回答