在Django模板中使用for循环显示多个chart.js图表

3

我有一个Django模板,我想显示以下内容:

  • 一些数据1
  • 数据1的图表
  • 一些数据2
  • 数据2的图表
  • 一些数据3
  • 数据3的图表

我的HTML中有一个Django模板循环,用于显示数据,然后是用于显示每个图表的画布。数据正确显示,我可以让它显示第一个图表。

我无法弄清楚的是:

如何显示多个图表?目前只显示第一个图表,而不是后续的图表 - 我认为可能是因为在每次迭代中canvas 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 %}
2个回答

2
为了引用画布,我将for循环索引附加到画布ID上:
<canvas id="myChart{{ forloop.counter0 }}" width="600" height="400">

然后在chart.js上下文中引用画布:

var ctx = document.getElementById("myChart" + {{ forloop.counter0 }}).getContext('2d'); 

2
马克,我需要同样的东西,那个对你有用吗?或者你找到了解决方案吗? - Daria M

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接