Django template how to look up a dictionary value with a variable
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops
--
Chapters
00:00 Question
00:36 Accepted answer (Score 448)
01:01 Answer 2 (Score 88)
01:26 Answer 3 (Score 46)
02:25 Answer 4 (Score 6)
02:50 Thank you
--
Full question
https://stackoverflow.com/questions/8000...
Accepted answer links:
[custom template filter]: https://docs.djangoproject.com/en/dev/ho...
Answer 3 links:
https://docs.djangoproject.com/en/dev/ho...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #django #templates #dictionary
#avk47
ACCEPTED ANSWER
Score 470
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 }}
ANSWER 2
Score 97
Fetch both the key and the value from the dictionary in the loop:
{% for key, value in mydict.items %}
{{ value }}
{% endfor %}
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.
ANSWER 3
Score 50
You can't by default. The dot is the separator / trigger for attribute lookup / key lookup / slice.
Dots have a special meaning in template rendering. A dot in a variable name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:
- Dictionary lookup. Example: foo["bar"]
- Attribute lookup. Example: foo.bar
- List-index lookup. Example: foo[bar]
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
@register.filter(name='lookup')
def lookup(value, arg):
return value[arg]
{{ mydict|lookup:item.name }}
ANSWER 4
Score 8
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 }}