How To Use The Context Variables Passed From Django In Javascript?
Solution 1:
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
safe
filter:
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.
Example:
<script>
$(function(){
var my_str = "{{ my_str }}";
var my_dict = {{ my_dict|safe }}; // no quotes herevar my_list = {{ my_list|safe }}; // no quotes here
});
</script>
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
defmy_view(...):
my_list = [...]
my_dict = {...}
context = {'my_list': json.dumps(my_list), 'my_dict': json.dumps(my_dict)}
return ...
var my_list = {{ my_list|safe }};
var my_dict = {{ my_dict|safe }};
Solution 2:
If the javascript code lies in the html template being rendered, you can use it in the normal way {{ context }}
. Else, declare a global in the html template and access that global from your separate js file.
Solution 3:
If you want to insert into Javascript then make sure to use escapejs, and in more advanced cases you may need to use JSON.parse;
var context = "{{ context }}"
If you are still having issues, then try;
var context = JSON.parse("{{ context|escapejs }}");
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. doc
Post a Comment for "How To Use The Context Variables Passed From Django In Javascript?"