hangc
hangc

Reputation: 5473

Injecting data into javascript with Python Flask

I am following the instructions from http://www.highcharts.com/docs/getting-started/your-first-chart to create a sample chart. I have saved the main chunk of javascript locally, and am add the <script src="/chart.js"></script> tag in my html to reference it.

On my side, I am using python flask to render a html template containing the script.

@app.route('/view', methods=['POST', 'GET'])
def show_graph_view():
    query= request.form['query']
    data = get_current_data(query)
    return render_template('graph.html', data=data)

I have a function to prepare some custom and current data I want to plot instead and I want the data to be available once the client brower loads. How do I add this data into the charts?

Upvotes: 0

Views: 932

Answers (2)

joram
joram

Reputation: 153

Is stumbled on this old answer in 2021 and I just wanted to add another option..

Injecting Python seems to mess with your Javascript, but you can actually do this:

<script>
    var names = []
    var i = 0
    // {% for i in range(0, names_len) %}      
        names[i++] = "{{names[i]}}";
    // {% endfor %}  
</script>

You can "comment-out" the injected Pyhton code, so your Javascript remains correct :)

Upvotes: 0

Robert Moskal
Robert Moskal

Reputation: 22553

Assuming a globally accessible function, just call it in the module with the data converted to json on the server with the tojson and safe filters.

<script type=text/javascript> doSomethingWith({{ data|tojson|safe }}); </script>

It's a bit hard to follow the logic when you mix together server side templating and client side scripting like this. But sometimes you gotta do it.

Upvotes: 1

Related Questions