2010-01-14 26 views
5

我的視圖代碼基本上是這樣的:在Django模板中訪問並行數組?

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]。這可能嗎?

+0

我總是可以寫這個用例的自定義模板標籤,但它似乎是大材小用。我討厭不得不說{{other_values | access:index}}。 – slacy 2010-01-14 19:54:07

回答

8

zip(some_values, other_values),然後用它在模板

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

我會使用'itertools.izip'來代替。 – 2010-01-14 19:49:45

+0

我寧願不必添加更多的上下文,這使得上下文數據相當多餘。此外,如果我改變我的模板(比如說,不再訪問這些並行數組),那麼我必須記得清理視圖代碼。它感覺它跨越了數據和表現之間的界限。 – slacy 2010-01-14 19:53:02

+1

@slacy:你的問題不純粹是關於表達。項目之間的關聯在兩個「並行」數組中很重要。 「並行」數組實際上只是等待創建的2元組。你*應該*將它們放在視圖函數中,因爲它們完全屬於邏輯。這就是爲什麼你要把它們放在一起。 – 2010-01-14 19:56:24