ステータス変数
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 |