Thymeleaf でどうやってフラグメント(部分テンプレート)を実現するのか書きました。 Rails では部分テンプレート (partial template) という言葉を使いますが、 Thymeleaf ではフラグメントという言葉のほうが一般的です。
環境
- Thymeleaf 2.1.4
フラグメント(部分テンプレート)を使う場合は、 th:include または th:replace を使います。 違いは、 指定したタグの中に展開するか(th:include)、 指定したタグを置き換えるか(th:replace)です。
サンプル
th:replace を使ったサンプルコードを紹介します。
まずはメインのテンプレートを記述します。
|
1 2 3 4 5 6 7 8 9 10 11 |
<div layout:decorator="layout/admin" xmlns:layout="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml"> <th:block layout:fragment="layout-content"> <div th:replace="/common/navigation"></div> <div class="row"> <p>This is main content</p> </div> <div th:replace="/common/navigation"></div> </th:block> </div> |
そして ディレクトリ resources/common に ファイル navigation.html を作成します。
|
1 2 3 4 |
<div class="row" th:fragment="nav"> [<a href="/home">Home</a>] [<a href="/second_home">Second Home</a>] </div> |
このようにすると、 th:replace 属性 をつけたところが navigation.html の内容に置き換えられます。
th:fragment 属性を使うともっと込み入った書き方ができます。 詳しくは Thymeleaf Page Layouts などをご覧ください。
