I am having a method in views.py as follows:
def index(self, request):
initial = get_initial()
context = {\"context\" : initial_topics}
template = lo
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.
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
You can access the context variable inside the HTML script
tag.
Still, some rules apply:
safe
filter.Example:
<script>
$(function(){
var my_str = "{{ my_str }}";
var my_dict = {{ my_dict|safe }};
var my_list = {{ my_list|safe }};
});
</script>
From above example you can see that you can access a Python dict or list as it is, without converting to json. But it might cause some errors. For example, if your dict contains True
and False
keywords but JS won't understand these and will raise error. In JS, the equivalent keywords are true
and false
. So, it's a good practice to convert dict and list to json before rendering.
Example:
import json
def my_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 }};