部分テンプレートの作成(Thymeleaf) - Spring Boot

  • 作成日:
  • 最終更新日:2025/10/11

部分テンプレートの作成

Spring Boot でよく使われるテンプレートエンジンのThymeleafでも、部分テンプレートを作成することができます。

src/main/resources/templatesfragments.htmlというファイルを作成します。

fragments.htmlを以下のようにします。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Fragments</title>
</head>
<body>
<!-- Headerフラグメント -->
<div th:fragment="header">
    <header>
        <h1>My Site Header</h1>
        <nav>
            <a href="/">Home</a>
        </nav>
    </header>
</div>

<!-- Footerフラグメント -->
<div th:fragment="footer">
    <footer>
        <p>© 2025 My Company</p>
    </footer>
</div>
</body>
</html>

テンプレートを呼び出すindex.htmlを以下のようにします。

<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<link rel="stylesheet" href="/css/style.css" />
<script src="/js/scripts.js"></script>
</head>
<body>
<div th:insert="~{fragments :: header}"></div>
<main>
    <p>content</p>
</main>
<div th:insert="~{fragments :: footer}"></div>
</body>
</html>

th:insert="~{fragments :: footer}のような書き方は、Tymeleaf 3.0 からの書き方です。

Spring Boot 3.x で使われている hymeleaf は 3.1 系です。

~{...} は テンプレート式(Template Expression) と呼ばれます。