views:

536

answers:

3

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.

A: 

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.

SapphireSun
Nevermind, I tested it and it doesn't work.
SapphireSun
Could not parse the remainder: '['works']' from 'test['works']'
Hellnar
Yep, you access dictionary values given a key using `.` notation in Django templates.
Dominic Rodger
Looking at the documentation, I'm getting the feeling that they didn't want spaces to be used. I'm seeing stuff like person.first_name, but never anything else. You can try looking at the parser code in django.template.__init__ but it is very long and complicated.
SapphireSun
This might be helpful: http://stackoverflow.com/questions/1275735/how-to-access-dictionary-element-in-django-template
SapphireSun
+2  A: 

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

luc
That looks like it'd work, but for the record, that's not a template tag, it's a filter (looks like whoever wrote that article made that mistake too).
Dominic Rodger
you are right! it is a filter. Thanks. I have fixed that
luc
+6  A: 

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

Ross
Don't forget to {% load myfilter %} in the template
Ross
@Ross - that linked website should come with a warning sign. Put on your sunglasses!
Dominic Rodger