1.はじめに
Thymeleafは画面側のテンプレートエンジンとしてよく使うので、この前にjspを使う場合も多いけど、二つの使い方は全然違いますと思い、今日はThymeleafの使い方を簡単にまとめてみます。
2.まとめ
-
式の構文
-
SpEL 式 ${value}
-
[[${value}]]
SpEL を使いましたら、オブジェクトの中身をそのままアクセスできます。<p><span th:text="${object.property}"></span></p>
-
*{value}
指定されたオブジェクトを基に、プロパティをアクセス<div th:object="${session. user}" > <p>Name: <span th: text=" *{firstName}" >Sebastian</span>. </p> <p>Surname: <span th: text=" *{lastName}" >Pepper</span>. </p> <p>Nationality: <span th: text=" *{nationality}" >Saturn</span>. </p> </div>
-
#{...}
通常は静的画面の場合、propertiesファイルに定義された中身をhtmlに埋め込みたいの際、以下の通り、やりまし ょう。
/WEB-INF/templates/app.htmlを新規して、ソースを埋め込み<p th: text=" #{app.welcome}" >This text will not be show! </p>
後は、WEB-INF/templates/app.propertiesを作って、テキストを埋め込み
app.welcome=this messages is from app.properties!
上記の通り、やりましたら、"This text will not be show!"の代わりに"this messages is from app.properties!"を表示されることになります。
-
th:とは
Thymeleafが特有のth:属性名です。 -
テキストの置換
usernameの値をtdタグの間に埋め込みます。<td class="text" th:text="${username}" ></td>
-
リンクURL
通常は < a > タグの href 属性などに指定する<a th:href="@{/login}" class="login">登録</a>
-
divテンプレートの導入
普通にh:include,th:replaceを使います。例えば、ヘッダファイルを作って、別のHTMLに導入する場合
/WEBINF/templates/heater. html :<div th: fragment="header" > welcome to my homepage! </div>
HTMLへ導入するの例は以下の通りです。
```
<div th: replace=" /templates/header : : header" ></div>
```
-
th: onclick:
クリックのイベント<button th:onclick="'doClick()'"></button>
th:の機能がいろいろありますので、以下の例はご参考しましょう。
<script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"
<input id="msg" type="hidden" th:value="${msg}" />
<a th:remove="${status}!=0?all:none" >削除</a>
<span th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"></span>
...
-
演算子
-
条件演算子
条件演算子を使うと、trueの場合はvalue1を設定します、逆に、falseの場合はvalue2を設定します。<p th:text="true ? 'value1': 'value2'"></p>
-
論理演算子
論理演算を行う<p th:text="true && false || true and not true or !false"></p>
-
算術演算子
算術演算を行う<P th:text="(100 + 5 - 2 * 15 / 10) % 3"></P>
3.最後に
最後まで読んで頂いてとても嬉しいです!
ありがとうございました!
4.参考
以下を参考にさせていただきました。ありがとうございました。
Spring Boot总结(9)---Thymeleaf用法大全
Spring Boot で Thymeleaf 使い方メモ