2017-10-13 74 views
1

我有簡單的SpringBoot應用程序。一切工作正常,但是當我試圖讓的index.html,在那裏我更換片段,如下圖所示,我得到一個異常:更換片段時解決thymeleaf模板時出錯

org.thymeleaf.exceptions.TemplateInputException:錯誤解決模板「〜{佈局」模板可能不存在或可能不被任何配置的模板解析器(指數:2)進行訪問

這裏是我的代碼:

的build.gradle通過SPRING INITIALIZR產生:

buildscript { 
     ext { 
      springBootVersion = '1.5.7.RELEASE' 
     } 
     repositories { 
      mavenCentral() 
     } 
     dependencies { 
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") 
     } 
} 

apply plugin: 'java' 
apply plugin: 'eclipse' 
apply plugin: 'org.springframework.boot' 

group = 'com.bearcave' 
version = '0.0.1-SNAPSHOT' 
sourceCompatibility = 1.8 

repositories { 
    mavenCentral() 
} 

dependencies { 
    compile("org.springframework.boot:spring-boot-starter-data-jpa") 
    compile("org.springframework.boot:spring-boot-starter-thymeleaf") 
    compile("org.springframework.boot:spring-boot-starter-web") 

    runtime('org.postgresql:postgresql') 
    compileOnly('org.projectlombok:lombok') 
} 

主要:

@SpringBootApplication 
public class MessengerApplication { 

    public static void main(String[] args) { 
     SpringApplication.run(MessengerApplication.class, args); 
    } 
} 

控制器:

@Controller 
public class HelloWorldController { 

    @GetMapping("/") 
    public String home() { 
     return "index"; 
    } 
} 

指數:

<!DOCTYPE html> 
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{layout :: layout (~{::body})}"> 
<body> 
    <div><p>Hello world!</p></div> 
</body> 
</html> 

佈局:

<!doctype html> 
<html th:fragment="layout (template)" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml"> 

<head> 
    <title>Messenger</title> 
</head> 

<body> 
    <div th:replace="${template}"></div> 
</body> 
</html> 

據我所知,Spring Boot自動配置,.html頁面的默認路徑是資源/模板,所以我有。此外,當我不嘗試替換片段時(我收到帶有「Hello world!」文本的簡單頁面)沒有問題。

我能做些什麼才能使它正常工作?

回答

1

默認情況下,spring-boot-starter-thymeleaf使用Thymeleaf 2.1。在您的模板中,您正在使用在Thymeleaf 3.0中引入的片段表達式(~{})。這就是爲什麼你的表達沒有按預期解析並導致錯誤。

你必須升級你的Thymeleaf的依賴到較新的版本。 Documentation說明如何在由Maven管理的項目中執行此操作。我不熟悉Gradle,但我認爲它會是模擬的。據this entry,所有你需要做的是提供以下幾行你的build.gradle文件:

ext["thymeleaf.version"] = "3.0.2.RELEASE" 
ext["thymeleaf-layout-dialect.version"] = "2.1.1" 

之後,請您佈局文件中刪除重複xmlns:th屬性(您提供兩次在html標籤內)。

這應該可以解決您的問題。

0

在您的layout.html中,您已經爲元素html指定了屬性xmlns:th。重複會產生SAXParseException

使用你的模板語法如下:

指數。HTML

<!DOCTYPE html> 
<html xmlns:th="http://www.thymeleaf.org" th:replace="layout :: layout (template)"> 
<body> 
    <div><p>Hello world!</p></div> 
</body> 
</html> 

的layout.html

<!DOCTYPE html> 
<html th:fragment="layout (template)" xmlns:th="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Messenger</title> 
</head> 
<body> 
    <h1>Hello world from layout</h1> 
</body> 
</html> 

輸出將是:

你好從佈局

世界更多瞭解使用片段: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#including-template-fragments