How to use the context variables passed from Django in javascript?

前端 未结 3 878
盖世英雄少女心
盖世英雄少女心 2021-01-27 03:52

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

def index(self, request):
    initial = get_initial()
    context = {\"context\" : initial_topics}
    template = lo         


        
3条回答
  •  盖世英雄少女心
    2021-01-27 04:45

    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

提交回复
热议问题