Thymeleafを使用して各画面で共通のレイアウトを利用する

Thymeleaf を使用して、共通レイアウトを作成する方法について記載します。

Thymeleafの基本的な使用方法については、以下のドキュメントを参照してください。

以下のサンプルコードの動作確認環境については、 動作確認環境と依存ライブラリについて を参照してください。

実装例

共通レイアウトは、ThymeleafのFragments を使用して実現します。

例えば、

  • <head>内の定義

  • ヘッダーのレイアウト

  • フッターのレイアウト

を共通化したい場合は以下のような実装になります。

<head>を定義したフラグメント
<head xmlns:th="http://www.thymeleaf.org" th:fragment="head_fragment(title, scripts, links)">
  <meta charset="UTF-8">
  <title th:text="${title}"></title>
  <!-- 全画面共通のcssを定義します -->
  <link rel="stylesheet" type="text/css" th:href="@{/css/base.css}"/>
  <!-- 各画面専用のcssを定義します -->
  <th:block th:replace="${links}" />
  <!-- 全画面共通のjavascriptを定義します -->
  <script type="text/javascript" th:src="@{/scripts/base.js}"></script>
  <!-- 各画面専用のjavascriptを定義します -->
  <th:block th:replace="${scripts}" />
</head>
ヘッダーのフラグメント
<header xmlns:th="http://www.thymeleaf.org" th:fragment="header_fragment">
  サンプルアプリケーションのヘッダーです。
</header>
フッターのフラグメント
<footer xmlns:th="http://www.thymeleaf.org" th:fragment="footer_fragment" id="footer">
  サンプルアプリケーションのフッターです。
</footer>
ユーザ画面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!-- th:replaceを使用して、 <head>用のフラグメントを読込みます -->
<head th:replace="common/head :: head_fragment(title = 'サンプルアプリケーション', scripts = ~{::script}, links = ~{::link})">
  <!-- 当画面で使用するjavascript、cssをフラグメントに渡します -->
  <link rel="stylesheet" type="text/css" th:href="@{/css/user.css}"/>
  <script type="text/javascript" th:src="@{/scripts/user.js}"></script>
</head>
<body>
  <!-- th:replaceを使用して、 ヘッダー用のフラグメントを読込みます -->
  <div th:replace="common/header :: header_fragment"></div>
  <div id="contents">
    <!-- 全画面共通のcssで定義されているスタイルが適用されているため、フォントサイズが9pxになります -->
    <!-- 当画面専用のcssで定義されているスタイルが適用されているため、フォントカラーが赤色になります -->
    ここに各画面のコンテンツを記載します。
    <br/>
    <!-- 全画面共通のjavascriptで定義されているhello()を呼び出します -->
    <button type="button" onclick="hello()">hello</button>
    <!-- 当画面専用のjavascriptで定義されているthanks()を呼び出します -->
    <button type="button" onclick="thanks()">thanks</button>
  </div>
  <!-- th:replaceを使用して、 フッター用のフラグメントを読込みます -->
  <div th:replace="common/footer :: footer_fragment"></div>
</body>
</html>

Tip

Fragmentsを読込む方法として、以下の方法があります。

  • th:insert

  • th:replace

上記の使い分けについては、 Tutorial: Using Thymeleaf - Including template fragments を参照してください。

サンプル全体は template-engine-thymeleaf-sample を参照してください。