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

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

    
    

    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 }};
    

提交回复
热议问题