Django模板中带有空格的字典键 [英] dict keys with spaces in Django templates

查看:36
本文介绍了Django模板中带有空格的字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to present a dictionary from my view.py at the HTML template such as:

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

并在模板中:

这没有问题:

{{ test.works }}

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

But a dictionary key that is having an empty space between words such as 'this fails' doesn't work:

{{ test.this fails }}

我收到此错误:

无法解析余数:'失败' from 'this failed'

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

我怎样才能克服这个问题?我不是填充模型的人,所以我无法更改 dict 的键来删除空格.

How can I overcome this problem? I am not the one filling the models, so I can't change the keys of the dict to remove spaces.

推荐答案

你想要的过滤器类似于

The filter you want is something like

@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

这篇关于Django模板中带有空格的字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆