Spring Bootのth:*属性とは?主要な属性とその役割を徹底解説!
Thymeleaf の th:*
属性は、HTML テンプレート内で動的に値を設定するために使用されます。以下に主要な th:*
属性とその役割をまとめます。
Thymeleaf の th:*
属性一覧
属性名 | 説明 |
---|---|
th:text | 要素内のテキストを動的に設定 |
th:utext | HTML タグを含むテキストを動的に設定(エスケープしない) |
th:value | input 要素の value を設定 |
th:href | a タグの href を動的に設定 |
th:src | img や script の src を動的に設定 |
th:action | form の action を設定 |
th:method | form の method を設定 |
th:class | class 属性を動的に設定 |
th:style | style 属性を動的に設定 |
th:alt | img の alt を設定 |
th:title | title 属性を設定 |
th:each | コレクションをループ処理 |
th:if | 条件に応じて要素を表示 |
th:unless | 条件に応じて要素を非表示 |
th:switch / th:case | switch 条件分岐 |
th:object | *{} で参照するオブジェクトを指定 |
th:field | form の入力値とバインド |
th:selected | select の option を選択 |
th:checked | checkbox や radio を選択 |
th:disabled | disabled 属性を設定 |
th:readonly | readonly 属性を設定 |
th:hidden | hidden 属性を設定 |
th:remove | 指定した要素を削除 |
th:inline | JavaScript・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.html
のth: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 に埋め込む形で簡潔に記述できるのが特徴です。使いこなすことで、より柔軟なテンプレートを作成できます。
セイ・コンサルティング・グループの新人エンジニア研修のメニューへのリンク
投稿者プロフィール

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