Passing an Array from a Flask view to the javascri

2020-06-28 08:51发布

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 succeeded passing it onto the Flask template tags of the next view, but I can't figure out how to use this data inside the javascript code that will build the chart using Chart.js

For example:

After researching on Google, I tried this to pass the array of the chart labels to javascript. The issue I have is that only the first element is passed and the data type is now string instead of Array.

What would be the right way to do pass the values variable of routes.py to the labelsData variable in pie.html ?

Flask- routes.py

[...]
@app.route("/piechart/<twitterhandle>")
def pie(twitterhandle):

    from app.twitter_parser import twitter_parser as tp

    alltweets = tp.get_all_tweets(twitterhandle)
    word_dict = tp.word_count(alltweets)
    keywords_dict = tp.top10words(word_dict)

    # keywords_dict is a dictionnary containing the 10 most
    # used words as keys and their respective count as value
    values = [values for labels, values in keywords_dict]
    labels = [labels for labels, values in keywords_dict]
    colors = [ "#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA","#ABCDEF", "#DDDDDD", "#ABCABC", "#CAABB9", "#46F7F3", "#EFCDAB"]


    # Render the Template
    return render_template('pie.html', values=values, labels=labels,
            colors=colors)

pie.html

[...]    
<meta id="labels_data" data-labels={{labels}}>
<meta id="values_data" data-values={{values}}>
<meta id="colors_data" data-colors={{colors}}>
[...]
    <script>
        var labelsData=document.getElementById("labels_data").dataset.labels;
        var valuesData=document.getElementById("values_data").dataset.values;
        var colorsData=document.getElementById("colors_data").dataset.colors;

        new Chart(document.getElementById("pie-chart"), {
         type: 'pie',
          data: {
            labels: labelsData,
            datasets: [{
              label: "Pie Chart",
              backgroundColor: colorsData,
            data: valuesData
            }]
          },
          options: {
            title: {
              display: true,
              text: 'Pie Chart Title'
            }
          }
        });
      </script>

1条回答
够拽才男人
2楼-- · 2020-06-28 09:51

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()
查看更多
登录 后发表回答