1

I'm trying to use google charts to visualize some data. As described in docs, i put this code to my template:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var tmp = document.getElementById('result').value;
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]]
    );

    var options = {
      title: 'Company Performance',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
  }
</script>
<div id="curve_chart" style="width: 900px; height: 500px"></div>

And it works fine. But i need to pass some custom data, so i did:

views.py:

def home(request): 
    example = [
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]
    return render(request, 'home.html', {'example': example})

As example data i used the same array. Next i replaced array in javascript code to {{ example }}:

 var data = google.visualization.arrayToDataTable( {{example}} );

And nothing happens. Google chart isn't drawing on my webpage anymore.
What im doing wrong? Also i tried to use json.dumps in python code and it didn't worked for me.

1 Answer 1

1

You should simply turn your list of lists into valid json before you pass it to the template:

import json

def home(request): 
    example = [
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]
    example = json.dumps(example)
    return render(request, 'home.html', {'example': example})

Make sure you're using the safe template tag:

var data = google.visualization.arrayToDataTable( {{example|safe}} );

What is the error you're getting when you try that?

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, i tried it too, and tried to use JSON.parse() method in javascript but nothing. Well, the key is filter safe thats the answer, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.