Thymeleaf templates

Thymeleaf is one of the template engines that has built-in support in Spring Boot. Read more about Thymeleaf syntax.

Add dependency to your project

dependencies {
...
implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
}

Set default location for your templates in property file

# resource/application.properties
spring.thymeleaf.prefix=classpath:/templates

Suppose we have an article.html template in our templates directory. Then we can us it in controller

@GetMapping("/articles/{idArticle}")
fun showPage(@PathVariable idArticle: Long)
    = ModelAndView("/article").apply {
        // add objects, that will be passed to the template
        addObject("articleModel", srv.loadData(idArticle))
   }

If you run your Spring Boot application as a jar, you must add / before the template name.

multiple resolvers

You can add multiple resolvers for example for the different template locations. Thymeleaf has built-in resolvers, that can load external templates:

  • ClassLoaderTemplateResolver - resolves templates inside classpath
  • FileTemplateResolver - resolves template on file system
  • ServletContextTemplateResolver - can be used inside your servlet
  • UrlTemplateResource - resolves template from url;
  • SpringResourceTemplateResolver - resolves templates using Spring's Resource Resolution mechanism
Multiple resolvers

custom resolvers

You can define own resolver by implementing the ITemplateResolver interface or extend existing.

For example you can extend StringTemplateResolver class to create resolver that load template from database.

Ccustom resolver