2

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>
0

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

This is good but how about the scenario where the js is an external file in static/js folder and i want to pull it to my html file ?
@SaiPardhu You can use one script tag to create the variable/constant <script>const data: {{values | tojson}}</script> and then call it in another <script src="static/script.js"></script>. The tags must follow this order (experimented inside the <header> in Chrome 101.0.4951.54).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.