Passing an Array from a Flask view to the javascript code of another view

后端 未结 1 892
盖世英雄少女心
盖世英雄少女心 2021-02-11 08:55

I have an array of data (it\'s a python list in my flask view) obtained after parsing a twitter feed.

I want to use it to build a chart in another view.

I succe

1条回答
  •  感动是毒
    2021-02-11 09:47

    I tried your code in my local system, I finally got the answer in this SO Answer

    Flask provides a Jinja filter for this: tojson dumps the structure to a JSON string and marks it safe so that Jinja does not autoescape it.

    So we can just pass the values to Javascript and by adding this filter, we can pass these values to Javascript variables.

    Please refer my below snippet and let me know if there are any issues!

    HTML:

    
        
    
    
    
    

    Flask:

    from flask import Flask, render_template
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        values = [12, 19, 3, 5, 2, 3]
        labels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
        colors = ['#ff0000','#0000ff','#ffffe0','#008000','#800080','#FFA500']
        return render_template('pie.html', values=values, labels=labels, colors=colors)
    
    if __name__ == '__main__':
        app.run()
    

    0 讨论(0)
提交回复
热议问题