5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Thymeleafで条件に合う要素だけを表示する(コレクションフィルタリング)

Posted at
頭の中整理しながら記述してます。
間違いありましたらご指摘いただけるとありがたいです:bow_tone1:

エンティティクラス

カテゴリの例 : mystery, fantasy, history

@Getter
@Setter
public class Book{
    private String title;
    private String category;
    private int price;
}

コントローラクラス

サービス層でDBにある全ての本のデータを取得する処理をしたと仮定して。

@Controller
public class BookController{

    private final BookService bookService;
    
    BookController(BookService bookService){
        this.bookService = bookService;
    }
    
    @GetMapping("/")
    public viewBooks(Model model){
       List<Book> books = bookService.getAllbook();
       model.addAttribute("books", books);

       return "book-list";
    }
}

カテゴリごとに分けて表示 (その壱)

<ul th:each="book : ${books.?[#strings.contains(book.category, 'mystery')]}">
    <li th:text="${book.title}"></li>
</ul>

カテゴリごとに分けて表示 (その弐)

仮に発売日が1週間前の全ての本を表示するような場合
(バックエンド側で日付の条件付きで取得したと仮定)

<div th:with="newMysteryBooks=${books.?[#strings.contains(book.category, 'mystery')]}">
    <div th:if="${#lists.isEmpty(newMysteryBooks)}">
        <p>新刊はありません</p>
    </div>

    <div th:if="${!#lists.isEmpty(newMysteryBooks)}" th:each="book : ${newMysteryBooks}">
        <div>
            <p th:text="${book.title}"></p>
        </div>
    </div>
</div>

th:with="newMysteryBooks=${books.?[#strings.contains(category, 'mystery')]}"


th:with
ローカル変数の定義・・・ ローカル変数の有効範囲は、定義したタグ含むその内側

books.?[]
<iterable>.?[条件]
コレクションをフィルタリング

#strings.contains(category, 'mystery')
#strings.contains(検索対象文字列, 検索ワード)
検索対象文字列に検索ワードが含まれているか判定

数値で分ける

<tr th:each="book : ${books.?[price > 1000]}">
  <td th:text="${book.price}"></td>
</tr>

参考サイト

5
2
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?