How to use conditional statements in Thymeleaf in Spring Boot

How to use conditional statement If, else in Thymeleaf in Spring Boot. In this article, we will learn How to use conditional statements in Thymeleaf in the Spring Boot application.

What is a Conditional Statement?

In a programming language, conditional statements are those statements that handle decisions. Example: If-else statement.

In the thymeleaf template, to use a conditional statement we can use the following statements:

  • th-if and th-unless
  • th-switch
  • Inline condition

If – Unless in Thymeleaf

The th-if and th-unless attribute render an HTML element based on a condition provided. The condition is given using ${} notation. The first div will be executed if the condition is TRUE else the next div.

<div th:if="${condition}">
  <h3>execute if the condition is true...</h3>
</div>
<div th:unless="${condition}">
  <h3>execute if the condition is false...</h3>
</div>

Switch Statement in Thymeleaf

Instead of If-Unless, we can use the th-switch attribute. This switch is similar to switch statements we have used until now (C, CPP, Java).

<div th:switch="${condition}">
  <p th:case="${value1}">First case will be executed...</p>
  <p th:case="${value2}">Second case will be executed...</p>
  <p th:case="*">Default case...</p>
</div>

The thyme leaf will check the condition first and if the case is found then it will render the HTML code. Case * is the default case.

Inline Statement in Thymeleaf

This is another way to use the conditional statement.  This is called an Elvis operator. It is like a ternary operator.

<span th:text = "${condition} ? 'exp1' : 'exp2'">Expressions</span>

In thymeleaf, if the condition is true then statement exp1 will be executed else the exp2.

So, these are all the statements through which we can handle decision-making. Now, let us look at an example to achieve it.

Conditional statements in Thymeleaf in Spring Boot

Step 1: Open IDE STS- Spring Tool Suite

Step 2: Go to File > Spring Starter Project.

Step 3: Now, fill all the fields as shown below and click Next.

Step 4: Now, Add the dependencies of Thymeleaf and spring web and click Next > Finish.

Now, wait for some time and your project structure will be ready. Go to the pom.xml file and you will see the following dependency being added automatically.

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <optional>true</optional>
</dependency>

Project Structure

Configure application. properties file

#change the port number
server.port=8888

Create a Controller

Create a TestController to handle requests. The request for the web page will be handle by the handler methods in the controller.

TestController

package com.example.thymeleaf.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.thymeleaf.model.Mobile;

@Controller
public class TestController {

 @GetMapping("/")
 public String home(Model model) {
  Mobile mobile1 = new Mobile(101,"Samsung","4GB",1500);
  Mobile mobile2 = new Mobile(102,"IPhone","6GB",15000);
  Mobile mobile3 = new Mobile(103,"Red Mi",null,200);
  List<Mobile> list = new ArrayList<>();
  list.add(mobile1);
  list.add(mobile2);
  list.add(mobile3);
  
  model.addAttribute("mobileData", list);
  return "homePage";
 }
}
  • @Controller annotation marks the TestController class a Request Handler.
  • Every request coming for the ‘/’ URL will be handled by the home() method. It would redirect you to the homePage page.
  • Create an object of the Mobile class and add it to the list and then pass the list into the model inside the home() method.

Create a Model class

This class is created to hold the data of the application (to model the data of the application)

Mobile.java

package com.example.thymeleaf.model;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Mobile {

 private int id;
 private String name;
 private String ramSize;
 private long price;
}

Create a Template

homePage.html

In the spring boot application, adding a thymeleaf template is quite simple. Go to src/main/resources/template folder and create a homePage.html file.

<!DOCTYPE html>
<html xmlns:th="www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>If-Else</title>
</head>
<body style="background-color: #f0f4c3">
<h1>Using If-Unless</h1>
<p style="color: red">Displaying Mobile on the basis of RAM Size</p>
<div class="container text-center" th:each="mobile: ${mobileData}">
<!-- Now, we will display Mobile based on their price  -->

<div th:if="${mobile.ramSize == '4GB'}">
 Name :  <span th:text="${mobile.name}"></span><br/>
 RAM  :  <span th:text="${mobile.ramSize}"></span><br/>
 Price    :  <span th:text="${mobile.price}"></span>	
</div>
<hr>
<div th:if="${mobile.ramSize == '6GB'}">
 Name :  <span th:text="${mobile.name}"></span><br/>
 RAM  :  <span th:text="${mobile.ramSize}"></span><br/>
 Price   :  <span th:text="${mobile.price}"></span>	
</div>
<hr>
<div th:unless="${mobile.ramSize}">
 Name :  <span th:text="${mobile.name}"></span><br/>
 RAM  :  <span th:text="${mobile.ramSize}"></span><br/>
 Price   :  <span th:text="${mobile.price}"></span>
</div>
</div>
</body>
</html>

Here, th: each attribute is used to iterate over the list of mobile and then inside a div tag the size of RAM is checked using th:if=”${mobile.ramSize == ‘6GB’}”.

If this is TRUE the statements written inside the <span> tag will be rendered else the statement under the other div i.e th:unless=”${mobile.ramSize}” will be checked for FALSE condition.

Now, Run the ThymeleafLesson3Application class and Go to localhost:8888 and see the following output.

In this way, we have learned how to use conditional statements using if-unless.