如何将django上下文变量传递到JavaScript? [英] How do I pass django context variables into javascript?
本文介绍了如何将django上下文变量传递到JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
系列:[{
name:'Brands',
colorByPoint:true,
data:[{
name:'Microsoft Internet Explorer',
y:56.33
},{
name:'Chrome',
y:24.03,
已切片:true,
已选择:true
},{
名称:'Firefox',
y:10.38
},{
名称:'Safari',
y:4.77
},{
名称:'Opera',
y:0.91
},{
name:'Proprietary or Undetectable',
y:0.2
}]
如何将这个数据传递给我的javascript?
解决方案
在Python中,然后将它传递给你的scr ipt作为JSON对象。您需要使用像 django-argonauts 这样的库来安全地执行此操作。
在您的观点中:
data = {
'series':[
'name':'Brands',
'colorByPoint':true,
#etc ...
]
}
将此作为上下文变量传递给您的模板。
然后,在模板中: {%load argonauts%}
< script>
(function(){
var data = {{data | json}};
//对数据做
})();
< / script>
其中 | json
是提供的模板过滤器由Argonauts图书馆处理,它将妥善处理所有数据。
I'm using highcharts and it requires me to pass into it variables such as this
series: [{
name: 'Brands',
colorByPoint: true,
data: [{
name: 'Microsoft Internet Explorer',
y: 56.33
}, {
name: 'Chrome',
y: 24.03,
sliced: true,
selected: true
}, {
name: 'Firefox',
y: 10.38
}, {
name: 'Safari',
y: 4.77
}, {
name: 'Opera',
y: 0.91
}, {
name: 'Proprietary or Undetectable',
y: 0.2
}]
How would I pass this into my javascript?
解决方案
You can generate the data structure in Python, and then pass it to your script as a JSON object. You need to use a library like django-argonauts to do this safely.
In your view:
data = {
'series': [
'name': 'Brands',
'colorByPoint': true,
# etc...
]
}
Pass this as a context variable to your template.
Then, in the template:
{% load argonauts %}
<script>
(function () {
var data = {{ data|json }};
// do something with data
})();
</script>
Where |json
is a template filter provided by the Argonauts library, which will handle properly escaping all the data for you.
这篇关于如何将django上下文变量传递到JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文