Spring Bootのth:*属性とは?主要な属性とその役割を徹底解説!

Thymeleaf の th:* 属性は、HTML テンプレート内で動的に値を設定するために使用されます。以下に主要な th:* 属性とその役割をまとめます。


Thymeleaf の th:* 属性一覧

属性名説明
th:text要素内のテキストを動的に設定
th:utextHTML タグを含むテキストを動的に設定(エスケープしない)
th:valueinput 要素の value を設定
th:hrefa タグの href を動的に設定
th:srcimgscriptsrc を動的に設定
th:actionformaction を設定
th:methodformmethod を設定
th:classclass 属性を動的に設定
th:stylestyle 属性を動的に設定
th:altimgalt を設定
th:titletitle 属性を設定
th:eachコレクションをループ処理
th:if条件に応じて要素を表示
th:unless条件に応じて要素を非表示
th:switch / th:caseswitch 条件分岐
th:object*{} で参照するオブジェクトを指定
th:fieldform の入力値とバインド
th:selectedselectoption を選択
th:checkedcheckboxradio を選択
th:disableddisabled 属性を設定
th:readonlyreadonly 属性を設定
th:hiddenhidden 属性を設定
th:remove指定した要素を削除
th:inlineJavaScript・CSS で変数を埋め込む
th:blockテンプレート内のブロック定義
th:replace他のテンプレートに置き換え
th:insert他のテンプレートを挿入
th:include他のテンプレートを埋め込み

主要な th:* 属性の使用例

1. th:text(要素のテキストを動的に設定)

<p th:text="${message}">デフォルトテキスト</p>

  • ${message} = "こんにちは" の場合 → <p>こんにちは</p>

2. th:utext(HTMLを含むテキストを設定)

<p th:utext="${content}"></p>

  • ${content} = "<strong>太字</strong>" の場合 → <p><strong>太字</strong></p>
  • th:utext"u" は "unescaped"(エスケープなし) の略です。

3. th:href(リンクを動的に設定)

<a th:href="@{/home}">ホーム</a>

  • 生成結果: <a href="/home">ホーム</a>

4. th:each(ループ処理)

<ul>
    <li th:each="item : ${items}" th:text="${item}"></li>
</ul>

  • ${items} = ["A", "B", "C"] の場合
<ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
</ul>


5. th:if(条件による表示制御)

<p th:if="${isAdmin}">管理者メニュー</p>
  • ${isAdmin} = true の場合 → <p>管理者メニュー</p>
  • ${isAdmin} = false の場合 → 何も表示されない

6. th:switch / th:case(条件分岐)

<div th:switch="${status}">
    <p th:case="'success'">成功しました!</p>
    <p th:case="'error'">エラーが発生しました。</p>
    <p th:case="*">未定義のステータスです。</p>
</div>


7. th:field(フォームとのバインド)

<input type="text" th:field="*{name}" />

  • @ModelAttribute でバインドされた name プロパティの値が自動でセットされる。

8. th:selected / th:checked(フォームの選択状態)

<select th:field="*{gender}">
    <option value="male" th:selected="${gender == 'male'}">男性</option>
    <option value="female" th:selected="${gender == 'female'}">女性</option>
</select>


9. th:remove(要素の削除)

<p th:remove="all">この要素は削除されます</p>

  • レンダリング時に <p> タグごと削除される。

10. th:replace / th:insert(テンプレートの再利用)

<div th:replace="fragments/header :: header"></div>

  • fragments/header.htmlth:fragment="header" を挿入。

まとめ

  • th:text / th:utext … テキストを動的に設定
  • th:each … ループ処理
  • th:if / th:switch … 条件分岐
  • th:href / th:src … 属性の動的設定
  • th:field / th:selected / th:checked … フォームとの連携
  • th:remove / th:replace / th:insert … テンプレート管理

Thymeleaf の th:* は、HTML に埋め込む形で簡潔に記述できるのが特徴です。使いこなすことで、より柔軟なテンプレートを作成できます。

セイ・コンサルティング・グループの新人エンジニア研修のメニューへのリンク

春のロゴ アイコン by Icons8

投稿者プロフィール

山崎講師
山崎講師代表取締役
セイ・コンサルティング・グループ株式会社代表取締役。
岐阜県出身。
2000年創業、2004年会社設立。
IT企業向け人材育成研修歴業界歴20年以上。
すべての無駄を省いた費用対効果の高い「筋肉質」な研修を提供します!
この記事に間違い等ありましたらぜひお知らせください。