python - Django 模板中带空格的字典键

标签 python django django-templates whitespace

我正在尝试在 HTML 模板中从我的 view.py 中呈现字典,例如:

test = { 'works': True, 'this fails':False }

在模板中:

这没有问题:

{{ test.works }}

但是在单词之间有空格的字典键(例如“this fails”)不起作用:

{{ test.this fails }}

我收到这个错误:

Could not parse the remainder: ' fails' from 'this fails'

我该如何克服这个问题?我不是填充模型的人,所以我无法更改字典的键以删除空格。

最佳答案

你想要的过滤器是这样的

@register.filter(name='getkey')
def getkey(value, arg):
    return value[arg]

与一起使用

{{test|getkey:'this works'}}

来源:http://www.bhphp.com/blog4.php/2009/08/17/django-templates-and-dictionaries

关于python - Django 模板中带空格的字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1906129/

相关文章:

python - 更改 3D 图(Matplotlib)的垂直(z)轴的位置?

python - 如何配置 Python key 环以从 Windows 7 上的 Windows 凭据管理器中提取凭据?

python - 如何使用 Flask 应用程序工厂模式实现 Celery

python - django-debug-toolbar 没有出现

django:为什么 RequestContext 设置为 context_instance?

python - Django 模板 {% if %} : what does it take to be equal?

python - Postgresql 安装的默认位置?

django - 是否可以在部署在 heroku 上的应用程序上重置 django 迁移?

python - Django View 变量未在 html 中显示任何数据

python - Django查询集在查询中获取空值