1

I've already checked out some similar questions here: How can I pass data from Flask to JavaScript in a template?

I'm trying to create a google chart using this example , where my data is coming from a database query, which is then parsed and formatted to be passed through Google's datasource python library, then converted into a json string. From there it is supposed to be passed through a JavaScript function in my HTML file in order to populate the Google Charts table. This last part seems to be causing me trouble. Here is the meat of my function in flask:

    description =  {"count": ("number", "Count"),"type": ("string", "Type")}

    data=[]
    rows = cur.fetchall()
    # formats MySQL data for JSON string 
    for row in rows:
        js = {'type': row[0], 'count': row[1]}
        data.append(js)

    # Loading it into gviz_api.DataTable (from Google Charts template)
    data_table = gviz_api.DataTable(description)
    data_table.LoadData(data)

     # Create a JSON string. (from google charts template)
    json= data_table.ToJSon(columns_order=("type", "count"), order_by="count")



render_template('myhtml.html' , json=json)

at the end of my function in flask, which is then passed through the following JavaScript function in my html file here:

<script>
 ... 
// taken from the Google Charts example
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
var json = '{{ json }}'

function drawTable(json) {
  var json_table = new google.visualization.Table(document.getElementById('table_div_json'));
  var json_data = new google.visualization.DataTable((json), 0.6);
  json_table.draw(json_data, {showRowNumber: true});
}

The chart is not drawn and I am left with only the header for the chart. I don't believe this is an issue with the format of my data or the HTML portion (which I've left out), for it is taken straight from the Google Charts template, so I've been trying to find problems in my JavaScript (which I am fairly new to). Can this string not be passed to the JavaScript function in this fashion? What alternative ways can it be done? Any pointers and suggestions would be great.

Community
  • 1
  • 1
cmark
  • 13
  • 4
  • Open the rendered output in your browser's dev tools and see what Jinja assigns `var json = ` to. Does it look right? – Celeo Oct 30 '15 at 20:46

1 Answers1

1

Probably have to escape it, something like:

{{json | safe}}
reptilicus
  • 10,290
  • 6
  • 55
  • 79
  • After following the advice from @celeo as well as taking your advice to escape it, I updated the JavaScript drawTable() function to the following: `function drawTable()` instead of `function drawTable(json)` and that in conjunction with the escape gave me the desired output. Thanks! – cmark Nov 02 '15 at 21:12