Springboot-thymeleaf如何通过fragment包含另一个文件

步骤 1 : 可运行项目

本知识点是基于 上一个知识点 进行改进

首先下载一个简单的可运行项目作为演示:网盘链接https://t.cn/A6Alt9fg

下载后解压,比如解压到 E:projectspringboot 目录下

步骤 2 : 新增 include.html

新建一个 include.html 文件,然后里面用 th:fragment 标记代码片段。

  • footer1 是 不带参数的
  • footer2 是带参数的

这两种情况也是包含业务经常会用到的做法

<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
</head>
<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>

步骤 3 : 修改 test.html

使用的时候就按照如下方式:

<div th:replace="include::footer1" ></div>
<div th:replace="include::footer2(2020,2200)" ></div>

就达到了包含的效果,其中第二种可以传参。
除了 th:replace, 还可以用 th:insert, 区别:

  • th:insert :保留自己的主标签,保留 th:fragment 的主标签。
  • th:replace :不要自己的主标签,保留 th:fragment 的主标签。

完整 test.html:

<!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+222}" ></p>
</div>

<div class="showing">
    <div th:replace="include::footer1" ></div>
    <div th:replace="include::footer2(2020,2200)" ></div>
</div>

</body>    
</html>

步骤 4 : 重启测试

重新运行 Application,然后访问地址测试:

http://127.0.0.1:8080/thymeleaf/test

显示效果:

更多关于 Springboot_thymeleaf_包含 详细内容,点击学习: https://t.cn/A6Agc551

原文地址:https://www.cnblogs.com/newRyan/p/12813910.html