ミルラク

Thymeleafでドロップダウンリストを実装する

更新日: 2024-02-27

当サイトはアフィリエイト広告を利用しています。

Thymeleafを書籍で学びたい方やThymeleafと一緒にSpringも習得したい方におすすめな書籍です。
Springについての書籍ですが、Thymeleafの基本構文や他システムとの連携など30ページほど取り上げられています。
ThymeleafとSpringは親和性の高い技術なので、これを機にSpringを学んでみるのはいかがでしょうか?

実行環境

実行環境がない方は、こちらの記事を参考にしてください。

項目バージョン
OSmacOS Catalina
JDKOracle JDK@8
Thymeleaf3.1

Thymeleafでドロップダウンリストを実装する

ドロップダウンリスト

ドロップダウンリストの初期値は th:selected で実装します。active が指定した値と一致する場合、初期状態で選択された状態になります。

<label>
  部署
  <select name="department">
    <option value="100" th:selected="${active == '100'}">管理部</option>
    <option value="200" th:selected="${active == '200'}">人事部</option>
    <option value="300" th:selected="${active == '300'}">営業部</option>
    <option value="800" th:selected="${active == '800'}">情報システム部</option>
  </select>
</label>

th:eachを使用したドロップダウンリスト

th:each="department : ${departments}" でマップの要素を department という変数に格納します。格納後、th:text="${department.value}" で選択肢を表示します。
ドロップダウンリストの初期値は th:selected で実装します。activedepartment.key と一致する場合、初期状態で選択された状態になります。

th:eachこちらの記事で紹介しています。

<label>
  部署
  <select name="department-iteration">
    <th:block th:each="department : ${departments}">
        <option th:value="${department.key}" th:text="${department.value}" th:selected="${active == department.key}"></option>
    </th:block>
  </select>
</label>

複数選択可能なドロップダウンリスト

ドロップダウンリストの初期値は th:selected で実装します。actives に指定した値が含まれている場合、初期状態で選択された状態になります。
ドロップダウンリストは multiple を指定することで複数選択が可能なため、複数の初期値があることを想定して #lists.contains を使用していますが、th:selected="${active == 値}" を使用しても問題ありません。

#listsこちらの記事で紹介しています。

<label>
  部署
  <select multiple name="department-multiple">
    <option value="100" th:selected="${#lists.contains(actives, '100')}">管理部</option>
    <option value="200" th:selected="${#lists.contains(actives, '200')}">人事部</option>
    <option value="300" th:selected="${#lists.contains(actives, '300')}">営業部</option>
    <option value="800" th:selected="${#lists.contains(actives, '800')}">情報システム部</option>
  </select>
</label>

th:eachを使用した複数選択可能なドロップダウンリスト

th:each="department : ${departments}" でマップの要素を department という変数に格納します。格納後、th:text="${department.value}" で選択肢を表示します。

ドロップダウンリストの初期値は th:selected で実装します。activesdepartment.key が含まれている場合、初期状態で選択された状態になります。
ドロップダウンリストは multiple を指定することで複数選択が可能なため、複数の初期値があることを想定して #lists.contains を使用していますが、th:selected="${active == department.key}" を使用しても問題ありません。

th:eachこちらの記事#listsこちらの記事で紹介しています。

<label>
  部署
  <select multiple name="department-iteration-multiple">
    <th:block th:each="department : ${departments}">
      <option th:value="${department.key}" th:text="${department.value}" th:selected="${#lists.contains(actives, department.key)}"></option>
    </th:block>
  </select>
</label>

お疲れさまでした

Thymeleafでドロップダウンリストを実装する方法を紹介しました。
少しでも参考になれば幸いです。