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

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

    Since I can't comment, let me do this in the form of an answer:
    to build on culebrón's answer or Yuji 'Tomita' Tomita's answer, the dictionary passed into the function is in the form of a string, so perhaps use ast.literal_eval to convert the string to a dictionary first, like in this example.

    With this edit, the code should look like this:

    # code for custom template tag
    @register.filter(name='lookup')
    def lookup(value, arg):
        value_dict = ast.literal_eval(value)
        return value_dict.get(arg)
    
    
    {{ mydict|lookup:item.name }}
    

提交回复
热议问题