Loading
  • LIGHT

  • DARK

ROUTE

ルートゼロの
アクティビティ

Thymeleafで「$」「@」「*」はどう違う?初心者でもわかる使い分け完全ガイド

10

その記号、なんの意味があるの?

<p th:text="${user.name}">名前</p>
<img th:src="@{/images/logo.png}" />
<option th:value="*{id}">...</option>

Thymeleafの「記号たち」をひとつずつ解説

1. ${…}:変数を参照するための記号

<p th:text="${user.name}">名前</p>
@GetMapping("/profile")
public String profile(Model model) {
    model.addAttribute("user", new User("田中 太郎"));
    return "profile";
}
<p th:text="${user.name}">名前</p>

2. @{…}:URLを生成する記号

<a th:href="@{/users}">ユーザー一覧</a>
<a th:href="@{/user/{id}(id=${user.id})}">詳細を見る</a>

3. *{…}:フォームとバインディングされた変数参照

<input type="text" th:field="*{username}" />
@GetMapping("/register")
public String form(Model model) {
    model.addAttribute("userForm", new UserForm());
    return "register";
}
<form th:object="${userForm}">
    <input type="text" th:field="*{username}" />
</form>

 th:objectの本質:「参照元オブジェクトを切り替える」

<form th:object="${userForm}">
    <input type="text" th:field="*{username}" />
    <input type="email" th:field="*{email}" />
</form>

コントローラーから渡すオブジェクトのイメージをつかもう

public class UserForm {
    private String username;
    private String email;

    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

使い分けで迷ったら?よくあるミスと対処法

「*{}と${}のどっちを使えばいいの?」

before / after でチェック!

<form th:object="${userForm}">
    <input th:field="${username}" /> <!-- NG! -->
</form>
<form th:object="${userForm}">
    <input th:field="*{username}" />
</form>

記号の使い分けをマスターしよう


次のステップは?

【外部リンク】

【内部リンク】

RANKINGranking-icon

LATEST POSTS

もっとルートゼロを知りたいなら

DISCOVER MORE