12

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.

Wooble
  • 87,717
  • 12
  • 108
  • 131
Hellnar
  • 62,315
  • 79
  • 204
  • 279

3 Answers3

18

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
  • 241
  • 1
  • 5
2

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
  • 41,928
  • 25
  • 127
  • 172
  • 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 Dec 15 '09 at 09:34
  • It's not a mistake. It predates the term "template filter" by several years. (I am the author of the blog post.) – pushcx Feb 18 '20 at 03:53
-4

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
  • 9,170
  • 11
  • 46
  • 59
  • 1
    Could not parse the remainder: '['works']' from 'test['works']' – Hellnar Dec 15 '09 at 09:16
  • Yep, you access dictionary values given a key using `.` notation in Django templates. – Dominic Rodger Dec 15 '09 at 09:17
  • 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 Dec 15 '09 at 09:28
  • 1
    This might be helpful: http://stackoverflow.com/questions/1275735/how-to-access-dictionary-element-in-django-template – SapphireSun Dec 15 '09 at 09:30