Home >Backend Development >Python Tutorial >How to Access Dictionary Values with Variable Keys in Django Templates?
Django Templates: Accessing Dictionary Values with Variable Keys
Accessing dictionary values in Django templates is straightforward using the dot operator, i.e., {{ mydict.key }}. However, challenges arise when the key is itself a variable, particularly when it's a property of a loop variable.
Problem:
Consider the following situation:
mydict = {"key1":"value1", "key2":"value2"} {% for item in list %} {{ mydict.item.NAME }} # Attempt to look up mydict[item.NAME] {% endfor %}
Here, the mydict.item.NAME syntax fails.
Solution:
To resolve this issue, you can create a custom template filter:
from django.template.defaulttags import register @register.filter def get_item(dictionary, key): return dictionary.get(key)
Note that the get() method is used instead of dictionary[key] to handle the case where the key is absent (returning None instead of raising a KeyError).
Usage:
Once the filter is registered, you can access dictionary values using variable keys as follows:
{{ mydict|get_item:item.NAME }}
The above is the detailed content of How to Access Dictionary Values with Variable Keys in Django Templates?. For more information, please follow other related articles on the PHP Chinese website!