组态

要开始使用 Thymeleaf,请访问官方下载页面

Maven 依赖

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

Gradle 依赖

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

配置示例

从 3.0 版开始,Thymeleaf 仅支持 Java 配置。

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

viewResolver() 方法中,你可以设置视图的编码和内容类型。更多信息

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

templateEngine() 中,你可以添加自定义方言。例如,要添加 Spring Security 方言,你可以像这样 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;
}

templateResolver() 方法中查看 setter 的前缀和后缀。它告诉 Thymeleaf,每次控制器返回视图时,Thymeleaf 会在 webapp/views/目录中查看 html 的这些名称,并为你添加 .html 后缀。

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

Thymeleaf 将在 webapp/views/foo/目录中查找名为 my-index.html 的 html。根据上面的示例配置。