0

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?

Community
  • 1
  • 1
ivan
  • 665
  • 3
  • 8
  • 23

1 Answers1

2

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.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152
  • yea i noticed that about 20 mins ago but didn't know how to change that. Thank you! it worked like a charm. You are a life saver – ivan Nov 17 '13 at 06:50