使用变量访问Django模板中的dictionary元素 [英] Access a dictionary element in the Django template with a variable
问题描述
情况如下.我们渲染一个视图.
The situation is the following. We render a view.
返回渲染(请求,'test.html',{'db_object':db_object,'dict':dict}
在模板中,我们现在要使用 db_object.key
访问字典.在python中,您通常会执行 dict [db_object.key]
.在模板中,您可以执行 {{dict.some_key}}
来访问值.但是在以下情况下,您显然无法执行 {{dict.db_object.key}}
In the template we would now like to access the dictionary with db_object.key
. In python you would normally do dict[db_object.key]
. In the template you could do {{ dict.some_key }}
to access the value. But in the following situation you obviously can't do {{ dict.db_object.key }}
有没有办法做到这一点?
Is there a way to accomplish this?
推荐答案
This has been covered before, and the best solution I've found is to create a quick custom filter. In case that link goes dead, here's the code (which I did not write, but am providing as reference):
@register.filter
def get_item(dictionary, key): return dictionary.get(key)
在模板中:
{{ dict|get_item:object.key }}
当然,请确保在模板标签上调用load,以便渲染器可以看到它们.
Of course, make sure to call load on your template tags so they're visible to the renderer.
这篇关于使用变量访问Django模板中的dictionary元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!