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

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

No comments:

Post a Comment