23.THYMELEAF 如何通过 FRAGMENT 包含另一个文件举例

include.html

新建一个 include.html 文件,然后里面用 th:fragment 标记代码片段。
footer1 是 不带参数的
footer2 是带参数的
这两种情况也是包含业务经常会用到的做法
include.html
1
2
3
4
5
6
7
8
<html xmlns:th="http://www.thymeleaf.org">
<footer th:fragment="footer1"
   <p >All Rights Reserved</p>
</footer>
<footer th:fragment="footer2(start,now)"
   <p th:text="|${start} - ${now} All Rights Reserved|"></p>
</footer>
</html>
 步骤 5 : 

test.html

使用的时候就按照如下方式:
 
<div th:replace="include::footer1" ></div>
<div th:replace="include::footer2(2015,2018)" ></div>
 

就达到了包含的效果,其中第二种可以传参。
除了th:replace, 还可以用th:insert, 区别:
th:insert :保留自己的主标签,保留th:fragment的主标签。
th:replace :不要自己的主标签,保留th:fragment的主标签。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hello</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" href="../../webapp/static/css/style.css"th:href="@{/static/css/style.css}"/>
    <script type="text/javascript" src="../../webapp/static/js/thymeleaf.js" th:src="@{/static/js/thymeleaf.js}"></script>
     
    <style>
        h2{
            text-decoration: underline;
            font-size:0.9em;
            color:gray;
        }
    </style>       
</head>
<body>
 
<div class="showing">
    <h2>显示 转义和非转义的 html 文本</h2>
    <p th:text="${htmlContent}" ></p>
    <p th:utext="${htmlContent}" ></p>
</div>
 
<div class="showing">
    <h2>显示对象以及对象属性</h2>
    <p th:text="${currentProduct}" ></p>
    <p th:text="${currentProduct.name}" ></p>
    <p th:text="${currentProduct.getName()}" ></p>
</div>
 
<div class="showing" th:object="${currentProduct}">
    <h2>*{}方式显示属性</h2>
    <p th:text="*{name}" ></p>
</div>
 
<div class="showing">
    <h2>算数运算</h2>
    <p th:text="${currentProduct.price+999}" ></p>
</div>
 
<div class="showing">
    <div th:replace="include::footer1" ></div>
    <div th:replace="include::footer2(2015,2018)" ></div>
</div>
 
</body>
 
</html>
 步骤 6 : 

重启测试

重新运行 Application,然后访问地址测试:
 
http://127.0.0.1:8080/thymeleaf/test
 
在页面底部可以看到如图所示的版权信息,这个版权信息就是包含另一个页面的内容而来的。
先运行,看到效果,再学习

posted on 2019-01-04 17:02  我是司  阅读(671)  评论(0)    收藏  举报

导航