Django template how to look up a dictionary value with a variable

后端 未结 8 1516
面向向阳花
面向向阳花 2020-11-22 03:06
mydict = {\"key1\":\"value1\", \"key2\":\"value2\"}

The regular way to lookup a dictionary value in a Django template is {{ mydict.key1 }}

8条回答
  •  灰色年华
    2020-11-22 03:33

    Write a custom template filter:

    from django.template.defaulttags import register
    ...
    @register.filter
    def get_item(dictionary, key):
        return dictionary.get(key)
    

    (I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

    usage:

    {{ mydict|get_item:item.NAME }}
    

提交回复
热议问题