5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Thymeleaf】ステータス変数

Posted at

ステータス変数

th:eachを利用する場合、繰り返し処理中のステータスを知るためのステータス変数というものが用意されている。ステータス変数を利用する場合、th:each 属性の中で、繰り返し変数の後ろにカンマで区切ってステータス変数を定義する。以下の例ではstatを追加。

Controller.java
List<Player> players = new ArrayList<Player>();
players.add(new Player(1 , "Miura", "Kazuyoshi"));
players.add(new Player(2 , "Nakamura", "Shunsuke"));
players.add(new Player(3 , "Matsui", "Daisuke"));
model.addAttribute("players", players);
list.html
<tr th:each="player, stat : ${players}" th:object="${player}">
	<td th:text="*{id}"></td>
	<td th:text="*{lastName}"></td>
	<td th:text="*{firstName}"></td>
	<td th:text="${stat.index}"></td>
</tr>

index以外にも様々なステータス変数が用意されている。

ステータス変数 内容
index 0始まりの現在の「繰り返しインデックス」
count 1始まりの現在の「繰り返しインデックス」
size 繰り返し変数の全要素数
current 現在の要素オブジェクト
even 現在の繰り返し位置が偶数の場合true
odd 現在の繰り返し位置が奇数の場合true
first 現在の繰り返し処理が最初の場合はtrue
last 現在の繰り返し処理が最後の場合はtrue

参照

Tutorial: Using Thymeleaf (ja) 6.2 繰り返しステータスの保持

5
2
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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?