我在Flask应用程序中使用Chart.js。我通过labels
将变量legend
,values
和chart.html
传递给render_template
。
我的应用程序正在使用以下chart.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chart</title>
<script src='static/js/Chart.bundle.min.js'></script>
</head>
<body>
<center>
<h1>Simple Line Chart</h1>
<canvas id="bar-chart" width="300" height="200"></canvas>
</center>
<script>
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels : [{% for item in labels %}
"{{item}}",
{% endfor %}],
datasets: [
{
label: '{{ legend }}',
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data : [{% for item in values %}
{{item}},
{% endfor %}]
}
]
},
options: {
legend: { display: true },
title: {
display: true,
text: 'Test Chart'
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</body>
</html>
我想将脚本节分成一个单独的文件,但是当我将<script></script>
标签内的节粘贴到文件bar-chart.js
时,出现错误:
Uncaught SyntaxError: Unexpected token %
bar-chart.js
的第4行,如下所示:
labels : [{% for item in labels %}
。
这是我尝试使用的经过修订的chart.html和bar-chart.js:
bar-chart.js:
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels : [{% for item in labels %}
"{{item}}",
{% endfor %}],
datasets: [
{
label: '{{ legend }}',
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data : [{% for item in values %}
{{item}},
{% endfor %}]
}
]
},
options: {
legend: { display: true },
title: {
display: true,
text: 'Test Chart'
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
chart.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chart</title>
<script src='static/js/Chart.bundle.min.js'></script>
</head>
<body>
<center>
<h1>Simple Line Chart</h1>
<canvas id="bar-chart" width="300" height="200"></canvas>
</center>
<script type="text/javascript" src='static/js/charts/bar-chart.js'></script>
</body>
</html>
如何从Javascript文件中成功调用变量labels
,legend
和values
?