thymeleaf佈局

需求:從後臺控制器返回到success.html頁面,success.html中只有該頁面的主要內容部分(即不包括公共的部分),但是瀏覽器訪問的時候顯示的是完整的頁面佈局(即success.html頁面中不僅有主要的內容部分,還包括公共部分)。

首先在pom.xml中引入thymeleaf

<dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在common路徑下有一個主要的html頁面layout.html,在layout中引入引入thymeleaf,代碼如下:

 layout.html頁面引入了common/head.html頁面

<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.theamleaf.org">
<head>
</head>

<body>

<!--  公共部分 start -->
<div th:include="common/head :: headbar"></div>
<!--  公共部分 end -->

<!-- 被引入的部分 start -->
<div layout:fragment="maincontent"></div>
<!-- 被引入的部分 end -->

</body>
</html>

 common/head.html頁面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<body>
<div th:fragment='headbar'>
    頁頭部分
</div>
</body>
</html>

主內容頁面,例如success.html頁面,要想在success.html中寫Javascript並且被加載,需要在<script>標籤中加上th:inline="javascript"

<!DOCTYPE html>

<!-- 

layout:decorator="common/layout"是引入common/layout.html頁面,然後用success.html頁面中的 layout:fragment="maincontent"部分替換common/layout.html頁面中的<div layout:fragment="maincontent"></div>

-->
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.theamleaf.org" layout:decorator="common/layout">
<!-- begin::Head -->
<head>

<script  type="text/javascript"  th:inline="javascript">

// js代碼

</script>
</head>

<body>
<div layout:fragment="maincontent">
成功頁面
</div>
</body>
</html>

在後臺請求success頁面 

@Controller
@RequestMapping(value="/")
public class HelloController {

    @GetMapping(value="/success")
    public String success() {
        
        return "success";
    }
}

得到的頁面就是:

<!DOCTYPE html>

<html>

<body>

<!--  公共部分 start -->
<div>
    頁頭部分
</div>
<!--  公共部分 end -->

<!-- 被引入的部分 start -->
<div>
成功頁面
</div>
<!-- 被引入的部分 end -->

</body>
</html>

返回的是一個完整的頁面 (包括layout頁面中的公共部分)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章