To look up a dictionary value with a variable with a Python Django template, we can add a custom template filter.
For instance, we write
from django.template.defaulttags import register
##...
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
to use the register_filter
decorator to add the get_item
template filter.
In it, we call dictionary.get
with the key
to return the value of the given key
.
Then we use it by using
{{ mydict|get_item:item.NAME }}
in our template
We use get_item
with item.NAME
we the key
and mydict
as the dictionary
value.