LoginSignup
2
1

More than 1 year has passed since last update.

th:each 任意の回数分反復する方法

Posted at

springboot勉強中、
「thymeleafで任意の回数分反復を行いHTML上に出力したいな。」と思うことがありました。

しかし、私が知っていたth:eachの使い方は、

normalVersion
<tr th:each="test:${tests}">
    		<td th:text="${test.id}"></td>
    		<td th:text="${test.name}"></td>
    		<td th:text="${test.price}"></td>
    		<td th:text="${test.genreId}"></td>
		</tr>

という方法のみでした。
そこで調べてみると、#numbers.sequenceという方法を使えば任意の回数分eachを反復できることが
判明しました。
例えば、5回th:eachで反復したい時には、

fivetimesVersion
<tr th:each="i : ${#numbers.sequence(1,5)}">
    		<td th:text="${tests[i-1].id}"></td>
    		<td th:text="${tests[i-1].name}"></td>
    		<td th:text="${tests[i-1].price}"></td>
    		<td th:text="${tests[i-1].genreId}"></td>
		</tr>

このようにやると5回反復できました!
是非お試しを✨

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