Home > Software engineering >  Thymeleaf: Check if list contains a string containing a substring
Thymeleaf: Check if list contains a string containing a substring

Time:01-30

I have a combined check that needs to happen in Thymeleaf:

  • List contains an item - can be done as th:if="${#lists.contains(data, '...')}" if you know the exact string
  • Item contains a substring - When iterating, can be done as th:each="item : *{data}" th:if="${#strings.contains(item,'(')}" e.g. to check for the substring "(" among the items of the list

I need to display a UL tag if the list contains an item containing the substring "(". No iteration, just this combined condition. How do I achieve that in one line?

<ul th:if="..."> <!-- This must be a combined check, no iteration. I don't even want to output the UL if not satisfied -->
</ul>

CodePudding user response:

You can accomplish this with collection selection. Just test if the list size is greater than zero. Something like this will work:

<ul th:if="${#lists.size(data.?[#strings.contains(#this,'(')]) GT 0}">

</ul>

CodePudding user response:

Assume you have a list like this, for testing:

List<String> data = Stream.of("abc", "d(ef", "ghi")
        .collect(Collectors.toList());

You can use the following:

<ul th:if="${#strings.contains( #strings.listJoin(data,'') ,'(')}">
    bazinga
</ul>

This first concatenates each item in the list into a single string.

It then checks to see if that string contains any ( characters.

  • Related