I am having a method in views.py as follows:
def index(self, request):
initial = get_initial()
context = {\"context\" : initial_topics}
template = lo
You can access the context variable inside the HTML script
tag.
Still, some rules apply:
safe
filter.Example:
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 }};