LoginSignup
4
5

More than 5 years have passed since last update.

Thymeleaf:th:eachで出力するときに区切り文字を付けて出力する

Posted at

はじめに

Thymeleafでサクッとできるのに久々にやると忘れがちなのでメモしておく。

やりたいこと

Listなどのコレクションに格納された情報をthymeleafで出力する際、読点「、」や斜線「/」のような区切り文字を付けて出力させたい。

リストのイメージ
{
    "Fruits": [
        {
            "name": "りんご"
        },
        {
            "name": "みかん"
        },
        {
            "name": "バナナ"
        }
    ]
}
出力結果
りんご、みかん、バナナ

やり方

ステップ1 とりあえず出力

とりあえず出力
<th:block th:each="fruit:${fruits}">
  <span th:text="${fruit.name}"></span>
</th:block>

出力結果
りんごみかんバナナ

ステップ2 読点を表示する

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

もちろんこれだと、バナナの後ろに読点が出てしまいます。

出力結果
りんご、みかん、バナナ、

ステップ3 ステータス変数のlastパラメータを利用して条件分岐

<th:block th:each="fruit, iterStat:${fruits}"> <!-- ステータス変数はカンマ区切りで2つ目の引数として受け取れる -->
  <span th:text="${fruit.name}"></span>
  <span th:unless="${iterStat.last}"></span><!-- last変数はループの最後でtrueを返します -->
</th:block>

これで、ループの最後だけ「、」を表示しないようにできます:relaxed:

出力結果
りんご、みかん、バナナ

ステータス変数にはlast以外にもいくつかパラメータがあるので、覚えて使うとハッピーになれるかもしれません。
参考)Tutorial: Using Thymeleaf (ja) 6.2 繰り返しステータスの保持

おまけ

Tutorial: Using Thymeleaf にも書かれていますが、iterStatは明示的に書く必要がありません。
省略した場合、繰り返し変数(fruit)の後ろにStatを付けた変数名が暗黙的に作成されます。
可読性の兼ね合いで書いたほうがいいかなという気もしますが、こっちのほうがすっきりしますね。

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

おわり

4
5
1

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