You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多Maven模块下Thymeleaf跨模块引用HTML模板的实现方法

解决跨Maven模块引用Thymeleaf模板的问题

刚好之前帮同事处理过几乎一模一样的场景——多Maven模块下,想在A模块的Thymeleaf模板里引用B模块的HTML片段,结合你的情况(Thymeleaf 3.0.9.RELEASE + Spring,涉及moduleMain、moduleCore、module2、module3,要在module1和module2里用moduleCore的Share.html),给你说下可行的解决办法:

为什么你之前的方法无效?

Thymeleaf的th:include/th:insert本身是支持片段引用的,但前提是模板文件在Thymeleaf解析器能扫描到的统一路径下。你之前的问题就出在moduleCore的Share.html不在默认的模板扫描路径里,导致跨模块时解析器找不到这个文件。

具体解决方案

把所有模块(包括moduleCore、module1、module2)中的HTML模板文件,都放到各自模块的src/main/resources/web-inf/templates目录下——如果moduleCore的Share.html之前在别的路径,直接移到这个目录里就行。

完成这一步后,你在module1或module2的模板里,就可以正常使用th:include或th:insert引用Share.html了,比如:

<!-- 引用整个Share.html页面 -->
<th:include="Share"></th:include>

<!-- 引用Share.html中名为"share-content"的片段 -->
<th:insert="~{Share :: share-content}"></th:insert>

这么做的原因是,Spring框架会自动扫描所有Maven模块中web-inf/templates这个默认路径下的Thymeleaf模板资源,把它们纳入统一的模板解析池,这样跨模块引用自然就生效了。


内容的提问来源于stack exchange,提问作者newOne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:51:16