Thymeleaf: Output with a delimiter when outputting with th: each

Introduction

It's easy to forget if you do it after a long time even though you can do it quickly with Thymeleaf, so make a note of it.

Thing you want to do

When outputting information stored in a collection such as List with thymeleaf, I want to output it with a delimiter such as a comma "," or a diagonal line "/".

List image


{
	"Fruits": [
		{
			"name": "Apple"
		},
		{
			"name": "Mandarin orange"
		},
		{
			"name": "banana"
		}
	]
}

Output result


Apples, oranges, bananas

manner

Step 1 Output for the time being

Output for the time being


<th:block th:each="fruit:${fruits}">
  <span th:text="${fruit.name}"></span>
</th:block>

Output result


Apple orange banana

Step 2 Display the reading point

python


<th:block th:each="fruit:${fruits}">
  <span th:text="${fruit.name}"></span>
  <span>、</span>
</th:block>

Of course, this will put a comma behind the banana.

Output result


Apples, oranges, bananas,

Step 3 Conditional branching using the last parameter of the status variable

python


<th:block th:each="fruit, iterStat:${fruits}"> <!--Status variables can be received as the second argument, separated by commas-->
  <span th:text="${fruit.name}"></span>
  <span th:unless="${iterStat.last}">、</span><!--last variable returns true at the end of the loop-->
</th:block>

Now you can hide the "," only at the end of the loop: relaxed:

Output result


Apples, oranges, bananas

There are some parameters in the status variable besides last, so you may be happy if you remember and use them. Reference) [Tutorial: Using Thymeleaf (ja) 6.2 Retaining repeated status](https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf_ja.html#%E7%B9%B0%E3%82%8A% E8% BF% 94% E3% 81% 97% E3% 82% B9% E3% 83% 86% E3% 83% BC% E3% 82% BF% E3% 82% B9% E3% 81% AE% E4% BF% 9D% E6% 8C% 81)

bonus

As mentioned in Tutorial: Using Thymeleaf, iterStat does not need to be explicitly written. If omitted, a variable name with Stat added after the repeating variable (fruit) is implicitly created. I think it's better to write it in terms of readability, but this one is cleaner.

python


<th:block th:each="fruit :${fruits}">
  <span th:text="${fruit.name}"></span>
  <span th:unless="${fruitStat.last}">、</span>
</th:block>

end

Recommended Posts

Thymeleaf: Output with a delimiter when outputting with th: each
A note about th: field th: each th: object of thymeleaf
Using hidden type when PUT with Thymeleaf
04. I made a front end with SpringBoot + Thymeleaf