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>
I tried your code in my local system, I finally got the answer in this SO Answer
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: