5

I am having a method in views.py as follows:

def index(self, request):
    initial = get_initial()
    context = {"context" : initial_topics}
    template = loader.get_template('index.html')
    return HttpResponse(template.render(context, request))

How do I access the "context" dict in javascript ?? Like in my $(function(){});

Tricky coder
  • 75
  • 1
  • 1
  • 5

3 Answers3

17

You can access the context variable inside the HTML script tag.

Still, some rules apply:

  1. If the context variable is a string, surround the context variable in quotes.
  2. 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 }}');
xyres
  • 20,487
  • 3
  • 56
  • 85
  • Thanks. I am passing a dict {"one" : 1, "two":2} like this for example. after doing json.dumps. In my javascript end, whenI just did alert("{{context}}" it gave "{"one": 1, "two": 2}". Plase gelp – Tricky coder Apr 09 '17 at 09:43
  • @Trickycoder Hello. Sorry, my answer had some mistakes. I've fixed them and edited the whole answer and have added more explanation. Hope this helps you this time. – xyres Apr 09 '17 at 10:48
  • Is there any documentation on this? – Joshua Swain Oct 02 '20 at 16:42
  • Even when the context variable is just a string you should still use `escapejs`. Otherwise a Python string like `"foo \" \' bar"` would not be correctly represented in JS – zabbarob Sep 28 '22 at 16:59
3

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.

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
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

almost a beginner
  • 1,622
  • 2
  • 20
  • 41