Springboot-thymeleaf如何通过fragment包含另一个文件
步骤 1 : 可运行项目
本知识点是基于 上一个知识点 进行改进
首先下载一个简单的可运行项目作为演示:网盘链接:https://t.cn/A6Alt9fg
下载后解压,比如解压到 E:\project\springboot 目录下
步骤 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,然后访问地址测试:
显示效果:
更多关于 Springboot_thymeleaf_包含 详细内容,点击学习: https://t.cn/A6Agc551
分类:
Springboot
标签:
Springboot
, thymeleaf
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!