kam*_*aki 3 python django django-templates
我有一本这样的字典:
myDict = {key1: item1,
key2: item2}
Run Code Online (Sandbox Code Playgroud)
如果我有这样的嵌套字典,我如何通过在 django 模板中提供key1以及更多内容来获取item1:
myDict2 = {key1: {key11: item11,
key12: item12},
key2: {key21: item21,
key22: item22}}
Run Code Online (Sandbox Code Playgroud)
例如我怎样才能item22使用key22
我知道{{ myDict[key1] }}不起作用
简短的回答是查看Django 模板中的解决方案如何使用变量查找字典值,然后两次应用过滤器。
{{ myDict2|get_item:"key2"|get_item:"key22"}}
Run Code Online (Sandbox Code Playgroud)
更长的答案(大量来自我链接的答案)是:
from django.template.defaulttags import register
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
Run Code Online (Sandbox Code Playgroud)
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
],
'libraries': {
'custom_tags':'YOURAPP.template_tags.custom_tags'
}
},
},
]
Run Code Online (Sandbox Code Playgroud)
{% load custom_tags %}
{{ myDict2|get_item:"key2"|get_item:"key22"}}
Run Code Online (Sandbox Code Playgroud)
通常要迭代模板中的字典,如下所示......
{% for key, value in harvest_data.items %}
{{ key }} <br>
{% for key2,value2 in value.items %}
{{ key2 }} <br>
{% for key3, value3 in value2.items %}
{{ key3 }}:{{ value3 }} <br>
{% endfor %}
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
关于模板中的嵌套字典渲染,我认为这在这里得到了回答
| 归档时间: |
|
| 查看次数: |
6969 次 |
| 最近记录: |