我正在使用 Django 和 Python 3.7。在我的模板中,我可以看到它的输出
{{ articlestat.article.website.id }}
这是“4”。我有一本字典,传递到我的上下文,其键是数字。如果我执行以下操作
{{ website_stats.4 }}
我看到打印的值。但是如果我这样做
{{ website_stats[articlestat.article.website.id] }}
我收到错误
Could not parse the remainder: '[articlestat.article.website.id]' from 'website_stats[articlestat.article.website.id]'
所以我的问题是,当键存储在变量中时,如何访问模板上字典的值?我无法对按键进行硬编码。
最佳答案
您无法在 django 模板中使用此语法访问字典键。通常,我们使用 {{ my_dict.my_key }}
访问 key 。
但是,如果您传递像 articlestat.article.website
这样的变量,这当然不会起作用,所有的点都会把事情弄乱。即使没有点,点后面的名称也不能是变量,模板引擎使用该名称作为字符串来查找该对象的键或属性。 (检查https://code.djangoproject.com/ticket/12486)
如果您确实无法匹配 View 中的值(更容易处理),则需要一个简单的 custom template filter .
在应用的
templatetags
文件夹中,添加一个名为custom_filters.py
的文件,其中包含以下代码:from django.template import Library register = Library() @register.filter def lookup(d, key): return d.get(key) # simple access here, you can also raise exception in case key is not found
在需要此类字典访问的模板中,在顶部添加
{% load custom_filters %}
,并使用以下语法调用您的值:{{ website_stats|lookup:articlestat.article.website.id }}
关于python - 在 Django 模板中,当键存储在变量中时,如何打印字典中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57740685/