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

后端 未结 8 1502
面向向阳花
面向向阳花 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 }}
    
    0 讨论(0)
  • 2020-11-22 03:33

    For me creating a python file named template_filters.py in my App with below content did the job

    # coding=utf-8
    from django.template.base import Library
    
    register = Library()
    
    
    @register.filter
    def get_item(dictionary, key):
        return dictionary.get(key)
    

    usage is like what culebrón said :

    {{ mydict|get_item:item.NAME }}
    
    0 讨论(0)
提交回复
热议问题