LoginSignup
14
9

More than 5 years have passed since last update.

Chart.jsをThymeleaf×SpringBootで

Posted at

Chart.jsをThymeleafで使う

Chart.jsをThymeleafで使うおうとした時に、あれ?ってなったのでメモ書き
折れ線グラフにして表示したい値をコントローラーで用意して、ビューで表示するだけのサンプルです。

コントローラー

ビューに渡す値をModelに格納します。

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Chart {

    @RequestMapping("/chart")
    // ビュー側にグラフで使う値を渡すためにModelを引数にとっておきます。
    public String hello(Model model) {

        // グラフの横軸と縦軸の値を、それぞれString、int型の配列に格納しておきます。

        // 横軸
        // ラベルです。String型の配列に、適当に値を入れておきます。
        String label[] = {"a","b","c","d","e","f","g"};

        // 縦軸
        // 具体的な値です。int型で、この値も適当です。
        int point[] = {5,3,7,1,8,3,4,};

        // Modelに格納します。ビュー側でグラフ用の配列を受け取れるようにしておきます。
        model.addAttribute("label",label);
        model.addAttribute("point",point);

        return "chart";
    }

}

ビュー側

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
    <title>折れ線グラフサンプル</title>
</head>
<body>
    <canvas id="ChartDemo"></canvas>
    <script type="text/javascript" th:inline="javascript">
    /*<![CDATA[*/
    var ctx = document.getElementById("ChartDemo").getContext('2d');
    var ChartDemo = new Chart(ctx, {
        type: 'line',
        data: {
            // コントローラーで格納したlabelを変数式で取り出すだけ。
            labels: /*[[ ${label} ]]*/,
            datasets: [
                {
                    label: "Chart-1",
                    borderColor: 'rgb(255, 0, 0)',
                    lineTension: 0,
                    fill: false,
                    // 上記と同様、pointを変数式で取り出しているだけです。
                    data: /*[[ ${point} ]]*/,
                },
            ]
        },
        options: {
            responsive: true,
        }
    });
    /*]]>*/
    </script>
</body>
</html>

実行してみた

chartdemo.jpg

参考

Thymeleaf version 2.1.4の機能メモ
Thymeleafチートシート

14
9
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
14
9