21

Is there any way to check both null and empty condition in Thymeleaf?

Approach 1

1) .variable1?.variable2?.variable3
2) variable!=null 
3) variable!=''

If we combine two conditions like (variable!='' And variable!=null) I am having issue when rendering.

I am trying following sample

${#strings.concat(#strings.concat('class ',variable1?.variable2), ' ', variable1?.variable2?.variable3)}

I also used containsKey as well but it is behaving differently.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Pradeep
  • 1,947
  • 3
  • 22
  • 45

3 Answers3

71

Try ${#strings.isEmpty(variable)}.

From Tutorial | Using Thymeleaf | Strings:

/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 */
${#strings.isEmpty(name)}
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
21

In order to check null or empty string using thymeleaf expressions, Use this approach : ---

<div th:if= "${searchResults.results != null}">

OR, this :--

<div th:if= "${searchResults.results != ''}">

Furthermore, you can check the empty or null object on your controller itself and then send the response on your thymeleaf-html page accordingly, like this :--
1.) Your Controller :-

 List ls = //some data from you DAO
    if(ls.isEmpty()){
         model.addAttribute("response","NoData");
      }else{
         model.addAttribute("response",ls);
     }

2.) Then on your Thymleaf page :- - -

<th:block th:if="${response=='NoData'}"> No Data Found </th:block>

PS - I've answered the same question here which helps the questioner hope it helps you as well :-- ThymeLeaf: Not Equal expression in th:if

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Sumit
  • 917
  • 1
  • 7
  • 18
  • Hi Sumit I have already tried this .I need both null and empty condition as one single operation rather than as separate condition.I hope u understand what I need – Pradeep Jul 14 '18 at 17:47
  • For that use **'or'** in between 2 condition , like this :-- **
  • ** Put **""** properly otherwise your page would end up with error.
  • – Sumit Jul 15 '18 at 05:20
  • Moreover you can also use **'and'** in a similar way like **or** . Just put **and** in between 2 conditions and it'll work. – Sumit Jul 15 '18 at 05:30
  • hi Sumit I tried with all these approaches but no luck. Let me try one more time and update you .Thanks for your help – Pradeep Jul 16 '18 at 07:38
  • **'or' ** And **'and'** operator will definitely work with two conditions in thyemleaf cz I've been using the same approach in my project as well.Hope it works out for you as well. – Sumit Jul 16 '18 at 08:11