プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Thymeleaf Layout Dialectでテンプレート作成

SpringのWebアプリケーションでは画面部分にThymeleafを使用することが多い
Thymeleafの共通部分を共通レイアウト(テンプレート)として使いまわす方法を解説する
 
・layout.html:テンプレートとなるベースのページ
・list.html:テンプレートを利用するページ
 
 


build.gradleの設定

dependenciesブロックに下記を追記

implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:2.3.0'

 
 
ついでによく使うBootstrapもdependenciesブロックに追加

implementation 'org.webjars:bootstrap:4.3.1'
implementation 'org.webjars:jquery:3.4.1'

 
 


ベースとなるレイアウトファイル(layout.html)を作成

格納先:src/main/resources/templates
 

<!DOCTYPE html>
<!-- ポイント1 -->
<html xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" th:href="@{/webjars/bootstrap/4.3.1/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/css/styles.css}" href="/css/styles.css">
<title>Insert title here</title>
</head>
<body>
    <!-- ポイント2 -->
    <div layout:fragment="content">
        <div class="container">
            Insert content here
        </div>
    </div>
    <script th:src="@{/webjars/jquery/3.4.1/jquery.min.js}"></script>
    <script th:src="@{/webjars/bootstrap/4.3.1/js/bootstrap.min.js}"></script>
</body>
</html>

 

【ポイント】

1.「Thymeleaf Layout Dialect」を使う為の記述
・xmlns:th="http://www.thymeleaf.org"
・xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
 
2.「layout:fragment="部品名"」
 
 


テンプレートを利用するページ(list.html)を作成

<!DOCTYPE html>
<!-- ポイント1 -->
<html xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
    layout:decorate="layout">
<head>
<meta charset="UTF-8">
<title>顧客一覧</title>
</head>
<body>
    <!-- ポイント2 -->
    <div layout:fragment="content">
            .
            .
            .
    </div>
</body>
</html>

 

【ポイント】

1.「layout:decorate="テンプレートページ名"」
※拡張子不要
2.「layout:fragment="部品名"」
このブロックにページの内容を記述
 
 


※Groovy3.0になるまではアプリケーションを起動時にWARNINGが出るが問題ない模様