So I have a python flask application that routes to a site and passes along two lists:
def chart():
labels = ['x', 'y', 'z']
values = [100, 150, 100]
return render_template('chart.html',
labels=labels, values=values)
I use Chart.min.js and I can then use the lists in rendering a graph in my chart.html:
{% block body %}
<h1>Test chart</h1>
<canvas id="myChart" width="800" height="400"></canvas>
<p id="caption">chart displaying labels n' values</p>
<script type=text/javascript>
var ctx = document.getElementById('myChart');
var names = [
{% for item in labels %}
"{{ item }}",
{% endfor %}
];
var numbers = [
{% for item in values %}
{{ item }},
{% endfor %}
];
var chartData = {
labels: names,
datasets: [{
label: 'values',
data: numbers
}]
};
var myChart = new Chart(ctx, {
type: 'line',
data: chartData
});
</script>
{% endblock %}
Now this works fine and I get a nice pretty graph.
Then I wanted to put my JavaScript in a seperate file in the static folder for my flask application but I cannot find how I'm supposed to access the lists passed along to chart.htlm. I can render a graph just fine if I hardcode some data into the JS file but I can't seem to get the data provided by the python code..
var ctx = document.getElementById('myChart');
// var names = ['x', 'y', 'z'];
// var numbers = [100, 150, 100];
var chartData = {
labels: names,
datasets: [{
label: 'values',
data: numbers
}]
};
var myChart = new Chart(ctx, {
type: 'line',
data: chartData
});
I have tried to loop the contents of the lists from my python file into different containers such as <div>, <ol> and <ul>and access those through document.getElementById("") among some other attempts, can't really remember them all.
I have tried to find the answer on google but to no avail.
Any help is appreciated and I should mention that I'm new to these coding languages and frameworks so please have some oversight if what I am missing is obvious.
=== NEW WORKING VERSION ===
chart.html :
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', (event) => {
const myChart2 = document.getElementById('ChartOne');
drawChart(ChartOne, {{ labels| tojson }}, {{ values| tojson }}, ChartType.LINE);
});
</script>
<div>
<canvas id="ChartOne" width="800" height="400"></canvas>
<p id="caption">line chart displaying labels n' values</p>
</div>
script.js:
const ChartType = {
LINE: "line" // add more variables for more chart options
}
function drawEmployeeChart(ctx, labels, values, chartType) {
var chartData = {
labels: labels,
datasets: [{
label: 'values',
data: values,
}]
};
var myChart = new Chart(ctx, {
type: chartType,
data: chartData
});
}