Spring Boot | Using the Thymeleaf Engine

What Is Thymeleaf?

  • Thymeleaf is a template engine that generates text, HTML, XML, JavaScript, and CSS.
  • Templates can remain valid HTML.
  • It is recommended for Spring Boot applications instead of JSP.

Thymeleaf documentation

Hello World

Adding the Dependency

dependencies {
    compile 'org.springframework.boot:spring-boot-starter-web'
+   compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
    compile 'org.webjars:jquery-ui:1.11.4'
}

Implementing the Controller

Use @Controller instead of @RestController when returning templates. The returned string is a path relative to the templates package.

@Controller
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping(method=RequestMethod.GET)
    public String hello() {
        return "hello";
    }
}
<!DOCTYPE html>
<html>
  <head><title>Hello Thymeleaf</title></head>
  <body><h1>Hello Thymeleaf</h1></body>
</html>

Open http://localhost:8080/hello.

Including Values in the Page

Pass a Model to the controller method and add attributes.

public String hello(Model model) {
    Hoge hoge = new Hoge();
    hoge.id = 10;
    hoge.value = "hoge";
    model.addAttribute("myData", hoge);
    return "hello";
}

Define the Thymeleaf namespace and use th:text.

<html xmlns:th="http://www.thymeleaf.org">
  <body>
    <dl>
      <dt>id</dt>
      <dd th:text="${myData.id}"></dd>
      <dt>value</dt>
      <dd th:text="${myData.value}"></dd>
    </dl>
  </body>
</html>

Repeating Output

Add a collection to the model and iterate with th:each.

model.addAttribute("hogeList", list);
<dl th:each="hoge : ${hogeList}">
  <dt>id</dt>
  <dd th:text="${hoge.id}"></dd>
  <dt>value</dt>
  <dd th:text="${hoge.value}"></dd>
</dl>