Thymeleaf Basics (Spring Boot)

Add Dependency

# pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Project Structure

src/main/resources/templates/
├── index.html
├── users.html

Simple Controller

// Controller
@Controller
public class HomeController {

  @GetMapping("/")
  public String home(Model model) {
    model.addAttribute("name", "John");
    return "index";
  }
}

Simple View

<p th:text="${name}">Name</p>
# Output: John

Display Variables

<h3 th:text="${name}"></h3>
<h3 th:text="${user.email}"></h3>

Conditions

<p th:if="${name == 'John'}">Hello John</p>
<p th:unless="${name == 'John'}">Not John</p>

Loop (List)

// Controller
model.addAttribute("users", List.of("John","Jane","Mike"));

// HTML
<ul>
  <li th:each="u : ${users}" th:text="${u}"></li>
</ul>

Form Example

<form th:action="@{/save}" method="post" th:object="${user}">
  <input type="text" th:field="*{name}" />
  <input type="email" th:field="*{email}" />
  <button type="submit">Save</button>
</form>

Handle Form Submit

@PostMapping("/save")
public String save(@ModelAttribute User user) {
  System.out.println(user.getName());
  return "redirect:/";
}

Fragments (Reusable Layout)

# header.html
<div th:fragment="header">
  <h2>My App</h2>
</div>

# use it
<div th:replace="header :: header"></div>