You can access the context variable inside the HTML script
tag.
Still, some rules apply:
- If the context variable is a string, surround the context variable in quotes.
- If the context variable is a dict or a list, convert them to json in your view and use the
escapejs
filter. You can also use the safe
filter but with caution.
Warning: Never use safe
filter on untrusted data (such as data submitted by a user). Always sanitize the data (escape unsafe characters) before using the safe
filter. Read about XSS attacks to learn more.
You should convert the dict and list variables to json in your views because if there are any Python specific keywords, such as True
or False
or None
in the dict, JS won't understand them and will raise an error.
In JS, the equivalent keywords are true
, false
and null
. So, converting dicts and lists to json will transform the data into a JS compatible format.
Example:
import json
def my_view(...):
my_string = 'hello'
my_list = [...]
my_dict = {...}
context = {'my_list': json.dumps(my_list), 'my_dict': json.dumps(my_dict)}
return ...
var my_string = '{{ my_string }}';
// for lists and dicts, use JSON.parse() to convert
// them into JS objects
var my_list = JSON.parse('{{ my_list|escapejs }}');
var my_dict = JSON.parse('{{ my_dict|escapejs }}');