mydict = {\"key1\":\"value1\", \"key2\":\"value2\"}
The regular way to lookup a dictionary value in a Django template is {{ mydict.key1 }}
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 }}
For me creating a python file named template_filters.py
in my App with below content did the job
# coding=utf-8
from django.template.base import Library
register = Library()
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)
usage is like what culebrón said :
{{ mydict|get_item:item.NAME }}