【问题标题】:get dictionary value by key in django template在 django 模板中按键获取字典值
【发布时间】:2018-11-15 03:29:03
【问题描述】:

我有一本这样的字典:

myDict = {key1: item1,
          key2: item2}

如果我有这样的嵌套字典,我如何通过在 django 模板中提供 key1 来获得 item1 等等:

myDict2 = {key1: {key11: item11,
                  key12: item12},
           key2: {key21: item21,
                  key22: item22}}

例如,我如何使用key22 获得item22

我知道{{ myDict[key1] }} 不起作用

【问题讨论】:

标签: python django django-templates


【解决方案1】:

简短的回答是查看Django template how to look up a dictionary value with a variable 的解决方案,然后应用过滤器两次。

{{ myDict2|get_item:"key2"|get_item:"key22"}}

更长的答案(大量取自我链接到的答案)是:

  1. 在您的应用文件夹中创建一个文件夹 template_tags
  2. 在该文件夹 custom_tags.py 中创建一个文件
  3. 在 custom_tags.py 中有来自其他答案的代码:
from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)
  1. 在设置中注册您的自定义标签,添加库并保留其余模板。
TEMPLATES = [
    {
        ...   
        'OPTIONS': {
            'context_processors': [   
            ],

            'libraries': {
            'custom_tags':'YOURAPP.template_tags.custom_tags'
            }
        },
    },
]
  1. 在您的模板中:
{% load custom_tags %}

{{ myDict2|get_item:"key2"|get_item:"key22"}}

【讨论】:

  • 谢谢 Zev ,我想我检查了你提到的链接 50 次,但我不知道如何调用 get_item 两次; {{ myDict2|get_item:"key2"|get_item:"key22"}} 就是答案
【解决方案2】:

通常在这样的模板中遍历字典...

{% 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 %}

关于模板中的嵌套 dict 渲染,我认为这是在这里回答的

Django template in nested dictionary

【讨论】:

  • 感谢 Paddy,因为我有我不打算用于循环的确切密钥
猜你喜欢
  • 2019-03-28
  • 2015-05-23
  • 2013-11-18
  • 2018-04-14
  • 1970-01-01
  • 2019-12-13
  • 2013-11-13
  • 2019-06-18
相关资源
最近更新 更多