mydict = {"key1":"value1", "key2":"value2"}
The regular way to lookup a dictionary value in a Django template is {{ mydict.key1 }}, {{ mydict.key2 }}. What if the key is a loop variable? ie:
{% for item in list %} # where item has an attribute NAME
{{ mydict.item.NAME }} # I want to look up mydict[item.NAME]
{% endfor %}
mydict.item.NAME fails. How to fix this?
Write a custom template filter:
(I use
.getso that if the key is absent, it returns none. If you dodictionary[key]it will raise aKeyErrorthen.)usage: