Thymeleafを使ってheaderとheadとfooterの共通化

こんばんは、エキサイト株式会社の中尾です。

今回はThymeleafを使ったheaderとheadの共通化を説明します。

公式documentに書いている通りですが、記載します。

www.thymeleaf.org

まず、gradleに以下をimplementationします。

    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf:2.7.2'

index.htmlhead.htmlheader.html を作成します。

th:replace を呼び出す側からfileを指定(htmlを省略)、呼び出される側に th:fragment で値を受け取れるようにします。

以下、具体的なhtmlファイルです。

index.html

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/head :: head_fragment(title = 'ユーザ検索', scripts = ~{}, links = ~{})"></head>
<!-- index.html専用のjs,cssがないので {} を空で渡す-->
<body>

<div th:replace="common/header :: header_fragment"></div>

<div class="container-fluid">
    <div class="row">
<!-- main コンテンツはここから -->
        <span>hello world</span>
<!-- main コンテンツはここまで -->
    </div>
</div>

</body>
</html>

head.html

<head xmlns:th="http://www.thymeleaf.org" th:fragment="head_fragment(title, scripts, links)">
    <title th:text="${title}"></title>
    <!-- Bootstrap core CSS -->
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <!-- 各画面専用のscript,cssを定義します -->
    <th:block th:replace="${links}" />
    <th:block th:replace="${scripts}" />
</head>

header.html

<header xmlns:th="http://www.thymeleaf.org" th:fragment="header_fragment">
  サンプルアプリケーションのヘッダーです。
</header>

上記のhtmlを用意して、実行してアクセスします。 すると、htmlが以下のように出力されるはずです。

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
    <title>ユーザ検索</title>
    <!-- Bootstrap core CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">
    <!-- 各画面専用のscript,cssを定義します -->
<body>

<header xmlns:th="http://www.thymeleaf.org">
  サンプルアプリケーションのヘッダーです。
</header>

<div class="container-fluid">
    <div class="row">
<!-- main コンテンツはここから -->
        <span>hello world</span>
<!-- main コンテンツはここまで -->
    </div>
</div>

</body>
</html>

th:replace が別に分けてたhtmlに置き換わっていることがわかります。

Thymeleaf 3.0では推奨されなくなりましたが th:include もあります。