組態

要開始使用 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。根據上面的示例配置。