Thymeleafでcontainsを使用した実装

Thymeleafでcontainsを使用した実装

Thymeleafでcontainsを使用して文字列の中に特定の文字列が含まれているかどうかをチェックする方法を紹介します。
以下の例では、containsを使ってリスト内のアイテムが特定の値を含んでいるかをチェックする方法を示します。

例: 文字列がリストに含まれているかを確認する

コントローラー
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Arrays;
import java.util.List;

@Controller
public class SampleController {

  @GetMapping("/example")
  public String example(Model model) {
    List<String> items = Arrays.asList("apple", "banana", "cherry");
    model.addAttribute("items", items);
    model.addAttribute("searchTerm", "banana"); // チェックしたい文字列
    return "example";
  }
}
テンプレート (example.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>Contains Example</title>
</head>
<body>
  <ul>
    <li th:each="item : ${items}"
        th:if="${item.contains(searchTerm)}"
        th:text="${item}">Item</li>
  </ul>
</body>
</html>

説明

1. コントローラー

  • itemsというリストと、検索する文字列searchTermをモデルに追加します。

2. テンプレート

  • th:eachを使ってitemsリストをループします。
  • th:ifを使って、item.contains(searchTerm)がtrueの場合にのみ
  • 要素を表示します。
  • th:textでリストアイテムの内容を表示します。

このようにすることで、リスト内のアイテムの中に指定した文字列が含まれている場合にのみ、そのアイテムが表示されるようになります。