Django template how to look up a dictionary value with a variable Django template how to look up a dictionary value with a variable django django

Django template how to look up a dictionary value with a variable


Write a custom template filter:

from django.template.defaulttags import register...@register.filterdef 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 }}


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.


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 }}