我的視圖代碼基本上是這樣的:在Django模板中通過變量訪問字典?
context = Context()
context['my_dict'] = {'a': 4, 'b': 8, 'c': 15, 'd': 16, 'e': 23, 'f': 42 }
context['my_list'] = ['d', 'f', 'e', 'b', 'c', 'a']
什麼,我想在我的Django的模板做的是這樣的:
<ul>
{% for item in my_list %}
<li>{{ item }} : {{ my_dict.item }}</li>
{% endfor %}
</ul>
,我想這是輸出:
<ul>
<li> d : 16 </li>
<li> f : 42 </li>
<li> e : 23 </li>
<li> b : 8 </li>
<li> c : 15 </li>
<li> a : 4 </li>
</ul>
但是,通過{{ my_dict.item }}
通過變量名稱引用字典實際上並不起作用。我懷疑它是在內部做my_dict['item']
而不是my_dict[item]
。有什麼辦法可以解決這個問題嗎?
當然,我總是可以在視圖中說,添加更多的代碼:背景[ 'my_derefernced'] = [(V,上下文[my_dict] [V])爲以V context ['my_list']]但我寧願不必這樣做。這些指令可能相當大。 – slacy 2010-01-14 19:50:05
看看這個偉大的解決方案:http://stackoverflow.com/questions/35948/django-templates-and-variable-attributes – fiatjaf 2012-01-01 15:26:24
如果字跡很大,爲什麼不使用生成器?可能是這樣的:'context ['my_dereferenced'] =((v,context [my_dict] [v])for context ['my_list'])' – user193130 2015-03-20 17:25:52