【问题标题】:Accessing django template's dictionaries given a variable?在给定变量的情况下访问 django 模板的字典?
【发布时间】:2018-12-31 10:21:11
【问题描述】:
我的问题是是否有办法在给定键的情况下获取字典的值。例如,假设my_dictionary 是{1:'a', 2:'b', 3:'c'},我有一个属性是key,它等于1。我怎样才能获得'a'?我试过{{my_dictionary.key}}和{{my_dictionary.{{key}} }},但都没有工作。我的想法是用 python 做同样的事情,它是 my_dictionary[key] 但在 Django 模板中。
谢谢
【问题讨论】:
标签:
python
django
django-templates
【解决方案1】:
您可以通过以下方式实现:
{% for key, values in data.items %}
{% if key == 1 %}
{{ value }}
{% endif %}
{% endfor %}
【解决方案2】:
解决此问题的最佳方法是编写自定义模板过滤器:
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> }}