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

Thymeleaf:在片段参数中使用字面量触发TemplateInputException

解决Thymeleaf片段传参引发的TemplateInputException问题

你这是碰到了Thymeleaf片段传参的常见问题啦!咱们一步步来排查修复:

1. 先修正片段里的title标签逻辑

你的片段里用了th:replace="${title}",这会把整个<title>标签直接替换成传入的参数值,显然不是你想要的效果——你应该是想设置title标签的文本内容,所以把th:replace改成th:text:

<head th:fragment="common_header(title)">
  <title th:text="${title}">Default title</title>
  <meta charset="utf-8" />
  <!-- 其他头部内容 -->
</head>

2. 修正片段调用的参数传递语法

Thymeleaf 3+支持两种参数传递方式,选一种适合你的就行:

方式一:位置参数(简单直接,适合参数少的场景)

如果你的片段只有一个参数,直接传字面量即可:

<head th:replace="header::common_header('This should be real title')">
  <title>Just for template's sake...</title>
  <meta charset="utf-8" />
  ...
</head>

方式二:命名参数(参数多的时候更清晰)

如果用命名参数,要确保字面量被Thymeleaf正确解析,写法如下:

<head th:replace="header::common_header(title=${'This should be real title'})">
  <title>Just for template's sake...</title>
  <meta charset="utf-8" />
  ...
</head>

要是你用的是Thymeleaf 3.0.10及以上版本,还能使用更简化的命名参数写法:

<head th:replace="header::common_header(title='This should be real title')">
  <title>Just for template's sake...</title>
  <meta charset="utf-8" />
  ...
</head>

3. 检查片段模板的路径是否正确

最后别忘了确认header是正确的模板路径:

  • 如果片段文件放在src/main/resources/templates/header.html,那header::common_header是没问题的
  • 如果片段在子目录里(比如src/main/resources/templates/fragments/header.html),那得写成fragments/header::common_header

按照上面的步骤调整后,这个异常应该就能解决啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:48:13