如何将我的上下文变量传递给 Django 中的 javascript 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8683922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:03:42  来源:igfitidea点击:

How can I pass my context variables to a javascript file in Django?

javascriptdjangotemplates

提问by user963936

This question must be obvious but I can't figure it out.

这个问题一定很明显,但我想不通。

In a template, I link to a js file in my media directory. From that file, I would like to access a context variable like {{my_chart}}.

在模板中,我链接到媒体目录中的 js 文件。从该文件中,我想访问一个上下文变量,如 {{my_chart}}。

But is the syntax different?? Thank you!!

但是语法不同吗??谢谢!!

采纳答案by Andrzej Bobak

I don't think it's possible this way. If you want to access some data provided by the view, you have to pass it to the js function.

我不认为这是可能的。如果要访问视图提供的某些数据,则必须将其传递给 js 函数。

Example

例子

js file:

js文件:

my_cool_js_function(some_param){
    // do some cool stuff
}

view

看法

// some html code

my_cool_js_function({{param}})

hope this helps :)

希望这可以帮助 :)

回答by Brian Neal

In addition to Andrzej Bobak's answer, you can also generate a global variable in Javascript from your template. For example, your template might generate code like this:

除了 Andrzej Bobak 的回答之外,您还可以从您的模板在 Javascript 中生成一个全局变量。例如,您的模板可能会生成如下代码:

<script>
   var my_chart = {{ the_chart }};
</script>

Your script could then refer to my_chart.

然后您的脚本可以引用my_chart.

回答by mastachimp

I would also add because I ran into the error a few times that if the python variable is an object it will throw a syntax error unless you put it in quotes, in other words, within your template,

我还要补充一点,因为我遇到了几次错误,如果 python 变量是一个对象,它会抛出一个语法错误,除非你把它放在引号中,换句话说,在你的模板中,

<script>
   var my_var = '{{ python_object|escapejs }}';
</script>

Furthermore, before putting that object in the context it is best to first serialize it to JSON, or you'll end up having to do string parsing. I found also that date objects needed to be converted to strings before this step.

此外,在将该对象放入上下文之前,最好先将其序列化为 JSON,否则您最终将不得不进行字符串解析。我还发现在此步骤之前需要将日期对象转换为字符串。

import jsonpickle

context['python_object'] = jsonpickle.encode(python_object)

And finally, in the JS you can then iterate through the object properly and use the values as you probably would have in python by doing:

最后,在 JS 中,您可以正确地遍历对象并使用您在 python 中可能拥有的值,方法是:

var my_var_parsed = jQuery.parseJSON(my_var);