通过Django模板中的键访问字典 [英] Accessing dictionary by key in Django template
问题描述
{key1:value1,key2:value2}
被传入并循环通过键,值对很好,但是我没有找到一个优雅的解决方案,从视图中直接访问一个特定的键,比如说key1
,例如bu json.items [key1]。我可以使用一些if / then语句,但我宁愿直接做一个方法? 这是html模板中的循环代码:
{%for key,value in json.items%}
< li> {{key}} - {{value}} < /锂>
{%endfor%}
Django模板语言支持查找字典键,如下所示:
{{json.key1}}
请参阅变量和查找。
模板语言不提供显示 json [key]
,其中 key
是一个变量。您可以编写一个模板过滤器来执行此操作,如这个堆栈溢出问题。
I'm passing a dictionary from my view to a template. So {"key1":"value1","key2":"value2"}
is passed in and looping through key,value pairs is fine, however I've not found an elegant solution from access directly in the view from a specific key, say "key1"
for example bu json.items["key1"]. I could use some if/then statements, but I'd rather do directly is there a way?
Here is looping code in the html template:
{% for key, value in json.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
The Django template language supports looking up dictionary keys as follows:
{{ json.key1 }}
See the template docs on variables and lookups.
The template language does not provide a way to display json[key]
, where key
is a variable. You can write a template filter to do this, as suggested in the answers to this Stack Overflow question.
这篇关于通过Django模板中的键访问字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!