Home >Backend Development >Python Tutorial >How to Access Dictionary Values with Variable Keys in Django Templates?

How to Access Dictionary Values with Variable Keys in Django Templates?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 05:37:17468browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn