user3080600
user3080600

Reputation: 1359

How do I pass django context variables into javascript?

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?

Upvotes: 0

Views: 742

Answers (1)

solarissmoke
solarissmoke

Reputation: 31404

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.

Upvotes: 2

Related Questions