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?
For me creating a python file named
template_filters.py
in my App with below content did the jobusage is like what culebrón said :
You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.
But you can make a filter which lets you pass in an argument:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters
I had a similar situation. However I used a different solution.
In my model I create a property that does the dictionary lookup. In the template I then use the property.
In my model: -
In my template: -
Write a custom template filter:
(I use
.get
so that if the key is absent, it returns none. If you dodictionary[key]
it will raise aKeyError
then.)usage:
Fetch both the key and the value from the dictionary in the loop:
I find this easier to read and it avoids the need for special coding. I usually need the key and the value inside the loop anyway.