Use variable as dictionary key in Django template

后端 未结 4 1608
野的像风
野的像风 2020-11-27 04:23

I\'d like to use a variable as an key in a dictionary in a Django template. I can\'t for the life of me figure out how to do it. If I have a product with a name or ID field,

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 04:37

    Building on eviltnan's answer, his filter will raise an exception if key isn't a key of dict.

    Filters should never raise exceptions, but should fail gracefully. This is a more robust/complete answer:

    @register.filter
    def keyvalue(dict, key):    
        try:
            return dict[key]
        except KeyError:
            return ''
    

    Basically, this would do the same as dict.get(key, '') in Python code, and could also be written that way if you don't want to include the try/except block, although it is more explicit.

提交回复
热议问题