Send graph values to Chart.js template with Python Flask

0๐Ÿ‘

โœ…

As always, after not coding for a few hours comes the answer. It occurred to me to create each graph inside a function (like this):

function chartFruitJuice(fruits) {
    const ctx = document.getElementById('myChart');
    const background_color = ['#33a3ec', '#ffce55', '#4ac1c1', '#ff00ff00'];
    var myChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['Orange', 'Apple', 'Pineaple'],
            datasets: [{
                data: fruits,
                backgroundColor: background_color,
                borderWidth: 10,
                borderColor: "#fbfbfb"
            }]
        }, options: {
            scales: {
                display: false
            },
            animation: {
                duration: 1000,
                animateRotate: true,
                render: false
            },
            plugins: {
                datalabels: {
                    display: true,
                    align: 'bottom',
                    backgroundColor: '#ccc',
                    borderRadius: 3,
                    font: {
                        size: 18,
                    },
                },
                title: {
                    display: true,
                    text: "Fruit juice"
                },
                legend: {
                    display: true,
                    position: 'bottom'
                }
            }
        }
    });
}

And in the HTML, pass the Flask values as parameters of said function:

<canvas id="myChart"></canvas>
<script>
    charFruitJuice({{ fruits | tojson | safe }});
</script>

Leave a comment