Thymeleaf でどうやってフラグメント(部分テンプレート)を実現するのか書きました。 In Rails, it is called partial template, but in Thymeleaf, usually called fragment.
Environment
- Thymeleaf 2.1.4
フラグメント(部分テンプレート)を使う場合は、 we use th:include or th:replace. 違いは、 指定したタグの中に展開するか(th:include)、 指定したタグを置き換えるか(th:replace)です。
Sample
Here’s sample code with th:replace.
Write the main template first.
|
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> |
And create the file navigation.html in the directory resources/common.
|
1 2 3 4 |
<div class="row" th:fragment="nav"> [<a href="/home">Home</a>] [<a href="/second_home">Second Home</a>] </div> |
Then, the tag with the attribute th:replace will be replaced to navigation.html content.
th:fragment attribute enables us to compose more complicated templates. Look at Thymeleaf Page Layouts for the detail
