dict keys with spaces in Django templates

2019-02-06 08:43发布

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

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

and in the template:

This works without a problem:

{{ test.works }}

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

{{ test.this fails }}

I get this error:

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

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.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-06 09:13

That doesn't look right to me. Can you do the following?

{{ test['works'] }} 
{{ test['this fails'] }}

This is how dictionary access in python typically works.

查看更多
祖国的老花朵
3楼-- · 2019-02-06 09:24

The filter you want is something like

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

And used with

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

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

查看更多
聊天终结者
4楼-- · 2019-02-06 09:33

I don't know any standard solution in Django. I think it is possible with a template filter.

You may be interested by this article http://push.cx/2007/django-template-tag-for-dictionary-access (the author is using template tag term but in fact it is a template filter)

I hope it helps

查看更多
登录 后发表回答