LoginSignup
8

More than 5 years have passed since last update.

posted at

updated at

Spring-boot / Thymeleaf で、bean の配列要素に動的にアクセスする

目的

入力フォームなどで使う bean オブジェクトの要素に配列を持たせて、その要素数が可変の場合でも Thymeleaf テンプレートで対応したい。

失敗例

以下のように th:each を使ってインデクスアクセスを書きたくなるが、これは上手くいかない

template.html
<table border="1">
  <!-- bars は配列 -->
  <tr th:each="bar,ix : ${bean.foo.bars}">
    <td th:text="${bean.foo.bar[${ix.index}].barMember}"></td>
  </tr>
</table>

成功例

以下のように、プリプロセッシング式 __ (アンダースコア2つ)を使うと上手くいく。

template.html
<table border="1">
  <tr th:each="bar,ix : ${bean.foo.bars}">
    <td th:text="${bean.foo.bar[__${ix.index}__].barMember}"></td>
  </tr>
</table>

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
What you can do with signing up
8