Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dict keys with spaces in Django templates

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.

like image 978
Hellnar Avatar asked Dec 15 '09 09:12

Hellnar


People also ask

Can dict keys have spaces?

The key is a case-insensitive scalar string and must be a valid IDL variable name (i.e., no spaces or special characters). You can retrieve elements by using either the bracket array notation or using the "dot" syntax like an IDL structure.

Can keys have spaces in Python?

Your keys can be any (string) you want. If you are using them for something internal - a space might not be the best idea. Otherwise - ok.

What does {% include %} in Django?

The include tag allows you include a template inside the current template. This is useful when you have a block of content that are the same for many pages.

What is context dictionary in Django?

A Context is a dictionary with variable names as the key and their values as the value. Hence, if your context for the above template looks like: {myvar1: 101, myvar2: 102} , when you pass this context to the template render method, {{ myvar1 }} would be replaced with 101 and {{ myvar2 }} with 102 in your template.


1 Answers

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

like image 145
Ross Avatar answered Sep 29 '22 21:09

Ross