python - 在 Django 模板中,当键存储在变量中时,如何打印字典中的值?

标签 python django python-3.x templates

我正在使用 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/

相关文章:

python - 将 python 列中以毫秒为单位的字符串时间转换为时间戳

python - 如何使用 pandas 从 .xls 文件中读取合并的单元格

django - Crispy 表单抛出 VariableDoesNotExist 错误,无法在表单上查找键 [html5_required]

python - Django:自定义中间件导致 NoneType 错误

python-3.x - API 网关 - Lambda 代理 - Python 内部服务器错误

python - 追加后如何打印列表中的所有元素?

python - 使用 Python 在 PostgreSQL 数据库上进行快速复杂的 SQL 查询

python - 如何从静态标签 wagtail 2.5 中的变量提供 webp

python - 将 CSV 导入 BigQuery 中的表时无法添加字段

python - 由 : java. io.IOException : error=13, Permission denied 引起