解決thymeleaf layout佈局不生效

今天使用thymeleaf layout佈局時老是不生效,特此把解決問題的步驟和幾個關鍵點記錄下來備忘。
1、檢查依賴
1.thymeleaf必備maven依賴:
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>${thymeleaf.version}</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring4</artifactId>
    <version>${thymeleaf.version}</version>
</dependency>

   

2.若是使用layout佈局,還須要添加:
<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
    <version>2.2.2</version>
</dependency>

  

2、配置視圖引擎
1.配置thymeleaf做爲視圖引擎
 
<!-- Thymeleaf View Resolver - implementation of Spring's ViewResolver interface -->
<bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />
    <property name="characterEncoding" value="UTF-8" />
</bean>
 
<!-- Thymeleaf Template Engine (Spring4-specific version) -->
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
    <property name="templateResolvers">
        <set>
            <ref bean="templateResolver" />
        </set>
    </property>
</bean>
 
<!-- Thymeleaf Template Resolver -->
<bean id="templateResolver" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
    <property name="prefix" value="/WEB-INF/templates/" />
    <property name="templateMode" value="HTML" />
    <property name="suffix" value=".html"></property>
    <property name="characterEncoding" value="UTF-8"></property>
</bean>

  

2.使用layout還須要在templateEngine添加以下節點:
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
    ……
    <property name="additionalDialects">
        <set>
            <bean class="nz.net.ultraq.thymeleaf.LayoutDialect"/>
        </set>
    </property>
</bean>

   

3、頁面html

task/layout.htmljava

<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>mysite</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="span3" th:insert="fragments/menu::menu"></div>
        <div class="span9" layout:fragment="content"></div>
    </div>
</div>
</body>
</html>

index.htmlspring

<!DOCTYPE html>
<html lang="en" layout:decorator="task/layout">
<head>
    <meta charset="utf-8">
    <title>index</title>
</head>
<body>
<div layout:fragment="content">
        <h1>
            Welcome!
        </h1>    
</div>
</body>
</html>
 
3、版本號
若是檢查了以上幾項仍是沒問題,最後還有一點值得注意的,就是thymeleaf和thymeleaf-layout-dialect的版本。
我最後就是調整了maven依賴的版本號,終於成功了。
相關文章
相關標籤/搜索