如何使用javascript中从Django传递的上下文变量? [英] How to use the context variables passed from Django in javascript?

查看:60
本文介绍了如何使用javascript中从Django传递的上下文变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在views.py中有一个方法,如下所示:

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))

如何在javascript中访问上下文字典?
就像我的$(function(){})一样;

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

推荐答案

您可以在HTML内访问上下文变量 script 标记。

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

不过,某些规则仍然适用:

Still, some rules apply:


  1. 如果上下文变量是字符串,请将上下文变量用引号引起来。

  2. 如果上下文变量是字典或列表,请不要使用报价。但是请使用安全过滤器。

  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.

示例:

<script>
$(function(){
    var my_str = "{{ my_str }}";
    var my_dict = {{ my_dict|safe }};
    var my_list = {{ my_list|safe }};
});
</script>

从上面的示例中,您可以访问Python字典或列出 ,而不转换为json。但这可能会导致一些错误。例如,如果您的字典包含 True False 关键字,但JS无法理解这些关键字,则会引发错误。在JS中,等效关键字为 true false 。因此,在呈现之前将dict和list转换为json是一个好习惯。

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.

示例:

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

这篇关于如何使用javascript中从Django传递的上下文变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆