thymeleaf で要素を部分置換

includeの場合は小要素として追加されます

include.html
<div id=”parent” th:include=”part”>text</div>

part.html
<div id=”children”>
part
</div>

と書いたら次のようになる。

<div id=”parent”>
<div id=”children”>
part
</div>
</div>

replaceの場合は要素が入れ替わります

replace.html
<div id=”parent” th:replace=”part”>text</div>

part.html
<div id=”children”>
part
</div>

と書いたら次のようになる。

<div id=”children”>
part
</div>

insertの場合は要素が挿入されます。

insert.html
<div id=”parent” th:insert=”part”>text</div>

part.html
<div id=”children”>
part
</div>

と書いたら次のようになる。

<div id=”parent”>
<div id=”children”>
part
</div>
</div>

実践

insert.html
<div id=”parent” th:insert=”テンプレート名”>text</div>

この構成のとき
templates
└── components
└── part.html

components/part が テンプレート名

insert.html
<div id=”parent” th:insert=”components/part”>text</div>

part.html
<div id=”children”>
part
</div>

こう書くと次のようになる。

insert.html
<div id=”parent”>
<div id=”children”>
part
</div>
</div>

th:insert=”components/part”

置換したい場合はreplace
中身を入れ替えたり・追加したい場合はinsert

templateName
templateName::selector
templateName::fragmentName

templateNameはHTMLのファイル名(構成を考慮して指定する必要がある)
selectorは
fragmentNameはth:fragment=””で指定した名前

fragment

th:fragmentと書くとその要素は部品化される。

例えば、次のような構成で
WEB-INF
└─views
└─layout
├─header.html
└─template.html

header.htmlのとある要素をfragment名headerで部品化する。

header.html
<!DOCTYPE html>
<html xmlns:th=”http://www.thymeleaf.org”>
<head>
<title>header</title>
</head>
<body>
<div th:fragment=”header” th:remove=”tag”>
<h1>
<a th:href=”@{/}”>Staff Management System</a>
</h1>
</div>
</body>

テンプレートで部品化したheader.htmlのheaderを置換する。
template.html
<!DOCTYPE html>
<html class=”no-js” xmlns:th=”http://www.thymeleaf.org”>
<head>
<meta charset=”utf-8″>
</head>
<body>
<div id=”header” th:replace=”~{layout/header::header}”></div>
</body>
</html>

公式サイトをじっくり読むのが一番早いかもな。
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf_ja.html#thfragment%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%9B%E3%81%9A%E3%81%AB%E3%83%95%E3%83%A9%E3%82%B0%E3%83%A1%E3%83%B3%E3%83%88%E3%82%92%E5%8F%82%E7%85%A7