Conditions

<!--  div presents if pageModel.isPublished is true -->
<div th:if="${pageModel.isPublished}">
   some content 
</div>

<div th:unless="${!pageModel.isPublished}">
   some content 
</div>

<!--  only one p will be in result-->
<div th:switch="${user.role}">
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p>
</div>

th:if and th:unless

There are two attributes that allow you to leave or delete an element depending on the condition:

  • th:if="condition" - leaves the element if condition true, otherwise remove element
  • th:unless="condition" - leaves the element if the condition is false; otherwise, remove the element. In other words, this is the inverse of th:if

Thymeleaf evaluates the specified expression with non-null value as true if:

  • value is a boolean and is true
  • value is a number and is non-zero
  • value is a character and is non-zero
  • value is a String and is not “false”, “off” or “no”
  • value is not a boolean, a number, a character or a String

th:switch

The th:switch attribute allows you to select a piece of code inside the parent element, depending on the value of the expression.
Nested elements use the th:case attribute. The * character means a default value.
Benefit is same as in other programming languages: using a condition expression only once and keeping code cleaner.