LoginSignup
0
0

Twig & Chart.jsでグラフ描画

Posted at
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<div>
    <canvas id="myChart"></canvas>
</div>

<script>
    {% set foo = ['A','B','C','D','E'] %}
    {% set bar = ['1','2','3','4','5'] %}
    
    const name = [];
    const value = [];
    {% for f in foo %}
    name.push('{{ f }}');
    {% endfor %}

    {% for b in bar %}
    value.push('{{ b }}');
    {% endfor %}


    const ctx = $('#myChart');

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: name,
            datasets: [{
                label: 'ex',
                data: value,
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>

スクリーンショット 2024-02-01 18.32.46.png


入れ替えがめんどくさかったらjsonに直でシリアライズして入れてもいい

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: {{ foo|json_encode(constant('JSON_UNESCAPED_UNICODE'))|raw }},
            datasets: [{
                label: 'ex',
                data: {{ bar|json_encode(constant('JSON_UNESCAPED_UNICODE'))|raw }},
                borderWidth: 1
            }]
        }
    });
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0