Thymeleaf 「th:if」属性 「th:unless」属性 「th:switch」属性

<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}" style="color:red"></span>
<div th:if="${session.bean == null}"> セッション中のスコープ変数 bean の値が null の場合 </div>

また、「th:if 」属性の値が null でない場合に true と判断する式のルールは以下の通り。
※ 値が null の場合は false と判断。
 boolean 型の true
 0 以外の数値
 0 以外の文字
 「 false 」、「 off 」、「 no 」以外の文字列
 真偽値、数値、文字、文字列以外の場合


また、「th:if 」とは逆に、条件を満たさない場合に特定の情報を出力する属性として「 th:unless 」属性
がある。

<span th:unless="${#fields.hasErrors('name')}" th:text="正常値です "></span>

Thymeleafでif-else文を作りたいのならばth:ifとth:unlessを組み合わせるのもいいかも


switch 文は「 th:switch 」属性と「 th:case 」属性を使用。「 th:switch 」属性には、評価の対象を記述。 そして、「 th:case 」属性には値を記述。
いずれかの「th:case 」属性の値が「 th:switch 」属性の値と一致する場合、対象の「 th:case 」属性の判
定 結果は true と評価され、対象のタグの処理結果が出力される。そして、それ以降の「 th:case 」属性
は 全て false と評価される。
また、「いずれの値にも一致しない場合」という条件で判定したい場合は「 th:case="*" 」と記述。

<div th:switch ="${user.Id}">
 <p th:case="1" 開発部 </p>
 <p th:case="2" 営業部 </p>
 <p th:case="*" 部署に所属していません </p>
</div>

Thymeleaf 固定値ブール属性(selected, checked)への値の追加

gender の値が 1 の場合は男性が、 2 の場合は女性が初期選択された状態になる

<input type="radio" name="gender" value="1" th:checked="${gender == 1}" /> 男性
<input type="radio" name="gender" value=" 2 " th:checked="${gender == 2}" /> 女性


category_id の値が 1 の場合は営業部が、 2 の場合は経理部が、 3 の場合は総務部が初期選択された状態となる。

<select name="dept_id ">
 <option value="1" th:selected="${category_id == 1}">営業部 </option>
 <option value="2" th:selected="${category_id == 2}">経理部 </option>
 <option value="3" th:selected="${category_id == 3}">総務部 </option>
</select>

Thymeleaf 属性値の前後への値の連結

既存の属性値の前後に別の値を連結したい場合は、「th:attrprepend 」属性と「 th:attrappend 」属性を
使用する。
「 th:attrprepend 」属性は属性値の前に連結し、「 th:attrappend 」属性は属性値の後ろに連結する。

<div class="area_" th:attrappend="class=${num}" />

また、特殊なものとして、「 class 」属性の属性値に連結する「 th:classappend 」属性と、「 style 」属性
の 属性値に連結する「 th:styleappend 」属性がある。

<div class="area_" th:classappend="${num}"

Thymeleaf 既に記述されたタグの属性値を変更

・th:attr
任意の属性に値を付与する際に利用。th:attr属性が記述されたタグの属性を変更できる。

<a href="dammy" th:attr="href=@{/items}" リンク </a>

また、複数の属性に値を付与したい場合は、カンマ区切りのリストを指定できる。

<img src="/sample.png" th:attr="src=@{/images/sample.png}, title=#{title}, alt=#{alt}" />

この属性単体では使用せず、if等と組み合わせて「一定の条件を満たした際に属性を変更する」という使い方をする。
しかしこの記法はあまり使用されていないとの事。
th:valueやth:actionなどがよく使用されている。