thymeleaf Getting started with thymeleaf Configuration


Example

To get started with Thymeleaf visit official download page.

Maven dependency

<dependency> 
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId> 
  <version>3.0.1.RELEASE</version> 
</dependency>

Gradle dependency

compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.1.RELEASE'

Example configuration

Starting from version 3.0, Thymeleaf supports only Java config.

public ViewResolver viewResolver() {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(templateEngine());
    resolver.setCharacterEncoding("UTF-8");
    resolver.setContentType("text/html; charset=UTF-8");
    return resolver;
}

In viewResolver() method you can setup e.g. encoding and content type for views. more information

public TemplateEngine templateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver());
    return engine;
}

In templateEngine(), you can add custom dialects. For example to add Spring Security dialect you can do this like this engine.addDialect(new SpringSecurityDialect());

public ITemplateResolver templateResolver() {
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setApplicationContext(applicationContext);
    resolver.setPrefix("/views/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode(TemplateMode.HTML);
    resolver.setCharacterEncoding("UTF-8");
    return resolver;
}

Look at setter for prefix and suffix in templateResolver() method. It tells Thymeleaf that, every time controller will return view, Thymeleaf will look these names that html in webapp/views/ directory and append .html suffix for you.

Example

@RequestMapping(value = "/")
public String homePage() {
    return "foo/my-index";
}

Thymeleaf will be looking html named my-index.html in webapp/views/foo/ directory. According to example configuration above.