How do I pass django context variables into javascript?

不羁的心 提交于 2019-12-12 06:03:58

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/43009740/how-do-i-pass-django-context-variables-into-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!