2024-04-20 12:59:41 发布
网友
我的问题是,如果给定一个键,是否有办法获得字典的值。例如,假设my_dictionary是{1:'a', 2:'b', 3:'c'},我有一个属性key,它等于1。如何获得'a'?我试过{{my_dictionary.key}}和{{my_dictionary.{{key}} }}但都没用。我的想法是和python一样,python是my_dictionary[key],但是在Django模板中。你知道吗
my_dictionary
{1:'a', 2:'b', 3:'c'}
key
'a'
{{my_dictionary.key}}
{{my_dictionary.{{key}} }}
my_dictionary[key]
谢谢
您可以通过以下方式实现:
{% 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> }}
您可以通过以下方式实现:
最好的方法是编写自定义模板筛选器:
模板中的用法:
相关问题 更多 >
编程相关推荐