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

如何在Thymeleaf中将JavaScript代码封装为可复用的fragment片段

Thymeleaf 引入外部JS代码片段失效解决方法
  • 修正片段引用路径
    你当前编写的test :: script指向的是模板根目录下test.html文件中的script片段,而你的实际片段文件存放在test/script.html,因此需要修改引用路径为:
<th:block layout:fragment="script">
    <div th:replace="test/script :: script"></div>
</th:block>
  • 确认布局方言依赖引入
    你使用了layout:命名空间,需要项目中已引入Thymeleaf Layout Dialect依赖,SpringBoot Maven项目可在pom.xml中添加如下配置:
<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
  • 验证渲染结果排查问题
  1. 打开页面开发者工具查看源码,若目标<script>代码未出现在页面中:
    确认test/script.html文件存放在项目的resources/templates/test/目录下,同时检查Thymeleaf模板解析器的前缀、后缀配置是否符合默认规则(默认前缀为classpath:/templates/,后缀为.html)。
  2. 若目标<script>代码已出现在页面中但未执行:
    查看控制台是否有JS报错,确认jQuery在你的脚本之前完成加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:12:04