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

后端 未结 8 1510
面向向阳花
面向向阳花 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

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

提交回复
热议问题