I am trying to pass a dictionary to a django template. In the django view, the variable is initialized and passed as such:
foo = {'a':'b'}
...
return render(request, 'template.html', {'foo': str(foo)}
In the template, I have
{{ foo|default:"{}"|safe}}
In case it's relevant, I have the above line in a jquery snippet. That snippet is failing because the dict is being rendered as
[{'a': u'b'}]
instead of what I expect:
[{'a': 'b'}]
It seems the safe filter is not removing the unicode u preceding the dict value 'b'. How do I do that?
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can't modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one's own need.
This flag tells Django that if a “safe” string is passed into your filter, the result will still be “safe” and if a non-safe string is passed in, Django will automatically escape it, if necessary. You can think of this as meaning “this filter is safe – it doesn't introduce any possibility of unsafe HTML.”
A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.
You should be using a function to explicitly convert it to JSON, because of a few subtle differences between JSON and the default Python stringification:
A string in JSON technically must be delimited with "
rather than '
, though parsers tend to accept the latter too (see the string rule on json.org)
Bool literals are lowercase
If your data contains things other than numbers, strings, lists and dicts, using str
on them will probably silently produce invalid JSON
Use a template filter such as django-jsonify:
{% load jsonify %}
...
{{ foo|jsonify }}
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