在给定变量的情况下访问Django模板的字典?

2024-04-20 12:59:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是,如果给定一个键,是否有办法获得字典的值。例如,假设my_dictionary{1:'a', 2:'b', 3:'c'},我有一个属性key,它等于1。如何获得'a'?我试过{{my_dictionary.key}}{{my_dictionary.{{key}} }}但都没用。我的想法是和python一样,python是my_dictionary[key],但是在Django模板中。你知道吗

谢谢


Tags: djangokey模板dictionary字典属性my办法
2条回答

您可以通过以下方式实现:

{% for key, values in data.items %}
   {% if key == 1 %}
      {{ value }}
   {% endif %}
{% endfor %}

最好的方法是编写自定义模板筛选器:

from django.template.defaulttags import register
register = Library()
...
@register.filter
def get_item(dictionary, key):
    # use .get so that if the key does not exist a KeyError will be raised
    return dictionary.get(key)

模板中的用法:

{{ data.items|get_item:<key_variable_here> }}

相关问题 更多 >