Henkes
Henkes

Reputation: 288

Flask, python dictionary to highcharts JS figure

I have a flask web-application. In this application I call "bar.htm"

return render_template('bar.htm', mapping=mapping)

where mapping is a dictionary like:

mapping = {'jack': 4098, 'sape': 4139}

Now I want to use this dictionary in a Highcharts bar graph. Where the bar graph with example data looks like this: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-rotated-labels/

(link to code to prevent huge question)

How can I implement my own dictionary in this JS file? datasection for highchart graph is like:

series: [{ name: 'Population', data: [<- this is where the variablemapping should come ['Shanghai', 23.7], ['Lagos', 16.1], ['Instanbul', 14.2], ['Karachi', 14.0], ['Mumbai', 12.5], ['Moscow', 12.1] ]

Upvotes: 2

Views: 1680

Answers (2)

Celeo
Celeo

Reputation: 5682

In your Python view:

mapping = [
    ['Shanghai', 23.7],
    ['Lagos', 16.1],
    ['Instanbul', 14.2],
    ['Karachi', 14.0],
    ['Mumbai', 12.5],
    ['Moscow', 12.1],
    ['Sao Paulo', 11.8],
    ['Beijing', 11.7],
    ['Guangzhou', 11.1],
    ['Delhi', 11.1],
    ['Shenzhen', 10.5],
    ['Seoul', 10.4],
    ['Jakarta', 10.0],
    ['Kinshasa', 9.3],
    ['Tianjin', 9.3],
    ['Tokyo', 9.0],
    ['Cairo', 8.9],
    ['Dhaka', 8.9],
    ['Mexico City', 8.9],
    ['Lima', 8.9]
]
return render_template('page.html', mapping=mapping)

And the HTML:

...
series: [{
    name: 'Population',
    data: {{ mapping|safe }},
    dataLabels: {
        ...

Define mapping as a list of lists, and then pass it to the template, using the safe filter.

Upvotes: 2

Sebastian Bochan
Sebastian Bochan

Reputation: 37588

You can use objects as data points, but you cannot use custom names. It should be something like {y:10, name: 'yourname'}. So only what you need is use your mapped objects in correct structure.

Upvotes: 0

Related Questions