Chartjs-Proper way to use a counter variable in HTML/Javascript

0👍

Try this:

{{ forloop.counter }} will return the current iteration count going on.

<ul>
    {% for object in objects %}

    <li>
        ...
        <script> 
            
            {% block jquery %}
            console.log(count);
            var endpoint = '/api/chart/data/';

            fetch(endpoint, {
                method: "GET",
            }).then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                ...
                eval('var chart_id = "myChart{{ forloop.counter }}"');
                eval('var ctx{{ forloop.counter }} = document.getElementById(chart_id)');

                eval('var myChart =  new Chart(ctx{{ forloop.counter }}, graph_data)');
                console.log("myChart{{ forloop.counter }}")
                })
                .catch((error) => {
                    console.log("Error:")
                    console.log(error);
                });

                        
            {% endblock %}
        </script>
        <canvas id= "myChart{{ forloop.counter }}" width="400" height="400"></canvas>
        ...
    </li>
    {% endfor %}
</ul>

Leave a comment