ivan
ivan

Reputation: 663

Using a flask variable as data source for highcharts

I am pulling data from my database and I am trying to set it up as the data for highcharts. I am passing a variable from flask to my template in the following format:

[{
  'x': 185.42,
  'team': 'PIT', 
  'y': 99.79,
  'position': 'QB', 
  'f_name': 'Bruce Gradkowski',
  'number': 5
},
{
  'x': 190.5,
  'team': 'DET', 
  'y': 105.23, 
  'position': 'QB', 
  'f_name': 'Matthew Stafford',
  'number': 9
}]

Basically it's a list full of dictionaries. If i copy and paste that text in the highcharts data section it works like a charm. I did not use jsonify or .getJSON (mostly because i have been looking it up online but still dont have a clear idea of how to pass the data from .getJSON to highcharts data).Instead I found this and thought it would be easier to pass the data to the template and inside the javascript function that sets the data for the highcharts series using {{ var_name }}. However, it does not work. Why? Can you give me an example of how to using .getJSON to set up the data for the Highcharts series or help me use the variable as the data source for the data?

Upvotes: 0

Views: 1174

Answers (1)

Miguel Grinberg
Miguel Grinberg

Reputation: 67527

Jinja2 escapes all variables as a safety measure. The array of dictionaries you show is rendered by default as:

[{'f_name': 'Bruce Gradkowski', 'team': 'PIT', 'number': 5, 'position': 'QB', 'y': 99.79, 'x': 185.42}, {'f_name': 'Matthew Stafford', 'team': 'DET', 'number': 9, 'position': 'QB', 'y': 105.23, 'x': 190.5}]

Note how the quotes were converted into HTML entities.

To prevent escaping you can add the safe filter as follows:

{{ var_name|safe }}

Note that this only works because Javascript and Python happen to have a similar syntax for arrays and dictionaries.

Upvotes: 2

Related Questions