我有一个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 %}
答案 0 :(得分:1)
因此,为了引用画布,我将forloop索引附加到画布id:
<canvas id="myChart{{ forloop.counter0 }}" width="600" height="400">
然后在chart.js上下文中引用画布:
var ctx = document.getElementById("myChart" + {{ forloop.counter0 }}).getContext('2d');
答案 1 :(得分:0)