[英]Display multiple chart.js charts using for loop in Django template
我有一個要在其中顯示的 Django 模板:
我的 HTML 中有一個 Django 模板循環,用於顯示數據,然后是用於顯示每個圖表的畫布。 數據顯示正確,我可以讓它顯示第一個圖表。
我想不通的是:
如何讓它顯示多個圖表? 目前它顯示第一個圖表但不顯示后續圖表 - 我想可能是因為畫布 ID 在每次迭代中始終相同?
模板
{% for session_data in ratings_by_theme %}
{{ session_data }}
<div class="myChart">
<canvas id="myChart" width="600" height="400"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [{% for label in chart_session_labels %} '{{ label }}', {% endfor %}],
datasets: [{
label: "Teacher",
data: {{ teacher_chart_data }}[{{ forloop.counter0 }}],
backgroundColor: 'rgba(255, 99, 132, 0.4)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
},
{
label: "Parent",
data: {{ parent_chart_data }}[{{ forloop.counter0 }}],
backgroundColor: 'rgba(255, 206, 86, 0.4)',
borderColor: 'rgba(255, 206, 86, 1)',
borderWidth: 1
},
{
label: "Learner",
data: {{ learner_chart_data }}[{{ forloop.counter0 }}],
backgroundColor: 'rgba(75, 192, 192, 0.4)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
},
{
label: "Leader",
data: {{ leader_chart_data }}[{{ forloop.counter0 }}],
backgroundColor: 'rgba(255, 159, 64, 0.4)',
borderColor: 'rgba(255, 159, 64, 1)',
borderWidth: 1
}
]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
</div>
{% endfor %}
因此,為了引用畫布,我將 forloop 索引附加到畫布 ID:
<canvas id="myChart{{ forloop.counter0 }}" width="600" height="400">
然后在 chart.js 上下文中引用畫布:
var ctx = document.getElementById("myChart" + {{ forloop.counter0 }}).getContext('2d');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.