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

后端 未结 1 891
盖世英雄少女心
盖世英雄少女心 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:

    <body>
        <canvas id="pie-chart" width="600" height="400"></canvas>
    </body>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
    <script>
        new Chart(document.getElementById("pie-chart"), {
             type: 'pie',
              data: {
                labels: {{labels | tojson}},
                datasets: [{
                  label: "Pie Chart",
                  backgroundColor: {{colors | tojson}},
                data: {{values | tojson}}
                }]
              },
              options: {
                title: {
                  display: true,
                  text: 'Pie Chart Title'
                }
              }
            });
    </script>
    

    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)
提交回复
热议问题