LoginSignup
4
0

More than 1 year has passed since last update.

Thymeleaf構文について

Posted at

Thymeleafとは

javaのテンプレートエンジンのひとつとなっており、ThymeleafはSpring Bootでの使用が推奨されています。MVCモデルでいう「V(ビュー)」にあたる部分です。

メリット

  • 独自のタグを使用しないので、普通のHTMLファイルをそのままJavaで使用できること。
  • 専用の記述があるが、かなり簡単で学習コストがかからない。
  • HTMLファイルに影響を与えない。

色々な変数式

変数式 ${...}
選択変数式 *{...}
メッセージ式 #{...}
リクURL式 @{...}
フラグメント式 ~{...}

構文一覧

th:field

サブミットする場合に指定

th:field=”${userForm.userId}”

th:fieldを使用すると、Javaクラスとバインドすることができる。
Modelに登録されたキー名.フィールド名でバインドできる。

th:text

画面へ文字列を出力する

<span th:text=”${form.userName}”>テスト</span>
結果
<span>ホゲータ</span>

上記”テスト”の部分は、th:textによる出力が優先される。

th:utext

HTMLとして出力したい場合。

ただし、スクリプトなどを書いてまうと、その通り実行されてしまうため、入力値を出力する箇所での使用はおすすめしません。

th:value

テキストボックスなどの値にセットする場合に使用する

<input type=”text” th:value=”${from.textValue}”/>
結果
<input type=”text” value=”1”/> 

th:object

指定したタグの中でthymeleafを使用する際に、変数名を省略できる

<form th:object=”${userFrom}”>
    <span th:text=”${userName}”>テスト</span>
</from>
結果
<form>
    <span>ホゲータ</span>
</form>

th:action

fromタグThymeleafで記述する場合に使用する。

URLを指定する場合、@で記述することで適切なURLを返却するようになる

<form th:action=”@{/user/index}”></form>
結果
<form action=”/user/index/”></form>

formタグのaction属性の内容を置換する。

th:if

式がtrueとなる場合にのみ、該当のタグを出力する

<span th:if=”${userForm.userId == null}”>ユーザーIDがありません</span>
<span th:if=”${userForm.userId  null}” th:text=”${userForm.userName}”>テスト</span>
結果
formクラスのuserIdがNULLの場合 : <span>ユーザーIDがありません</span>
formクラスのuserIdがNULLでない場合 : <span>ホゲータ</span>

th:each

配列・リストをループ処理する場合に使用する。
th:each=”ループ中の変数名 : ${ループする配列}”

<ul>
   <li th:each=”${items: userForm.Name}”></li>
<ui>
結果
<ul>
  <li>ホゲータ</li>
  <li>クワッス</li>
  <li>ニャオハ</li>
<ul>

th:block

HTMLとして出力されない、Thymeleaf専用のタグ

<label class="detail_label">
  <span class="title">担当エリア</span>
	// 値がnullの場合の処理
  <th:block th:if="${usersCreateForm.areas == null}">
    <span class="detail_data" th:text="null"></span>
  </th:block>
	// 値が入っているときの処理
  <th:block th:unless="${usersCreateForm.areas == null}">
    <span class="detail_data" th:text="*{areas.areasName}"></span>
  </th:block>
</label>

th:ifとth:unlessでif elseの書き方ができる。

値を入れる際にどこがnullなのか確認して条件分岐を書く。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0