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

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

    You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.

    Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

    • Dictionary lookup. Example: foo["bar"]
    • Attribute lookup. Example: foo.bar
    • List-index lookup. Example: foo[bar]

    But you can make a filter which lets you pass in an argument:

    https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

    @register.filter(name='lookup')
    def lookup(value, arg):
        return value[arg]
    
    {{ mydict|lookup:item.name }}
    

提交回复
热议问题