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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With