LoginSignup
5
3

More than 5 years have passed since last update.

Thymeleaf3でMap<String, Object>形式から表を出力する

Posted at

目的

Thymeleafで出力する項目が可変の表(table)を出力したいときに利用します。

実行環境

SpringBoot 2.0.3.RELEASE ( Thymeleaf 3.0.9.RELEASE )

Controllerと出力するデータ

Controllerからは、Map形式のものを渡します。ただしMapの出力順序を必ず定めたいので、LinkedHashMapを使っています。

package alphapz.thymeleaf.controller;


import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author A-pZ
 *
 */
@Controller
public class MatrixController {
    @GetMapping("")
    public ModelAndView display(ModelAndView mnv) {

        mnv.addObject("data", matrix);
        mnv.setViewName("index");

        return mnv;
    }

    private Map<String, Object> matrix = new LinkedHashMap<String, Object>() {{
        put("id","ID001");
        put("name","username");
        put("address","USER_ADDRESS");
    }};
}

View (Template)

dataの名前で先程のMapが格納されているので、Collection系を繰り返し表示する th:each で指定します。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
    <table>
        <thead class="thead-dark">
            <tr>
                <th th:each="entry : ${data}" th:text="${entry.key}"></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td th:each="entry : ${data}" th:text="${entry.value}"></td>
            </tr>
        </tbody>
    </table>
</body>
</html>

th:each で取り出した要素は、EntrySet なので、キー名は key、値は value から取得できます。

5
3
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
5
3