S-JIS[2017-10-21] 変更履歴

Thymeleaf th:each

Thymeleafのth:each属性のメモ。


概要

th:each属性は、タグを繰り返す指定。

th:each属性を付けたタグは、「th:each属性に指定したコレクション」の個数分出力される。


th:each属性の基本形は以下のようになる。

	th:each="変数名 : コレクション"

コレクション内の要素が変数(繰り返し用変数)に入り、「${変数名}」や「${変数名.プロパティー名}」で使用できる。


ステータス変数

また、要素毎のステータスを取得することも出来る。

	th:each="変数名, ステータス変数名 : コレクション"

これにより、例えば「${ステータス変数名.index}」でインデックス(0オリジン)、「${ステータス変数名.count}」で番号(1オリジン)を取得することが出来る。

名前 説明
index 現在のインデックス(0オリジン)
count 現在の番号(1オリジン)
size コレクションの要素数
current 現在のオブジェクト(繰り返し用変数と同じ)
even インデックスが偶数かどうか
odd インデックスが奇数かどうか
first 先頭かどうか
last 最後かどうか

ステータス変数を明示的に定義しない場合、繰り返し用変数名の末尾に「Stat」を付けたものがステータス変数として使用できる。


ステータス変数の例

ステータス変数の例。

src/main/java/com/example/demo/web/EachController.java:

package com.example.demo.web;

import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EachController {

	@RequestMapping(path = "example/each")
	public String init(Model model) {
		List<String> list = Arrays.asList("aa", "bb", "cc");
		model.addAttribute("list", list);

		return "each";
	}
}

src/main/resources/templates/each.html

	<table border="1">
		<tr>
			<th>element</th>
			<th>index</th>
			<th>count</th>
			<th>size</th>
			<th>current</th>
			<th>even</th>
			<th>odd</th>
			<th>first</th>
			<th>last</th>
		</tr>
		<tr th:each="element, elementStat : ${list}">
			<td th:text="${element}"></td>
			<td th:text="${elementStat.index}"></td>
			<td th:text="${elementStat.count}"></td>
			<td th:text="${elementStat.size}"></td>
			<td th:text="${elementStat.current}"></td>
			<td th:text="${elementStat.even}"></td>
			<td th:text="${elementStat.odd}"></td>
			<td th:text="${elementStat.first}"></td>
			<td th:text="${elementStat.last}"></td>
		</tr>
	</table>

↓生成された結果

element index count size current even odd first last
aa 0 1 3 aa true false true false
bb 1 2 3 bb false true false false
cc 2 3 3 cc true false false true

Thymeleafへ戻る / Spring Bootへ戻る / Spring Frameworkへ戻る / 技術メモへ戻る
メールの送信先:ひしだま