[Chartjs]-Passing an Array from a Flask view to the javascript code of another view

10๐Ÿ‘

โœ…

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()

Leave a comment