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

前端 未结 3 879
盖世英雄少女心
盖世英雄少女心 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:38

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-27 04:52

    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, don't use the quotes. But use the 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 }};
    
    0 讨论(0)
提交回复
热议问题