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

Thymeleaf 3中data-th-text含Not报错:无法解析表达式,如何解决?

解决Thymeleaf中data-th-text显示"Not Mounted"报错的问题

这个报错的核心原因是:Thymeleaf会将data-th-text属性内的内容当作表达式来解析,而"Not"是Thymeleaf内置的布尔否定运算符(类似!),所以它误以为你要写一个表达式,导致解析失败。

给你几个简单可行的解决方案:

方案1:用单引号包裹文本(最直接)

把"Not Mounted"用单引号括起来,明确告诉Thymeleaf这是一个字符串字面量,而非表达式:

<div class="form-group">
  <label for="status">Status:</label>
  <select data-th-field="*{status}" id="status" class="form-control">
    <option data-th-value="available" data-th-text="Available"></option>
    <option data-th-value="broken" data-th-text="Broken"></option>
    <option data-th-value="not mounted" data-th-text="'Not Mounted'"></option>
  </select>
</div>

方案2:使用Thymeleaf的文本字面量语法(可读性好)

用|符号包裹文本,这是Thymeleaf专门用于定义纯文本字面量的语法,适合不需要变量拼接的场景:

<div class="form-group">
  <label for="status">Status:</label>
  <select data-th-field="*{status}" id="status" class="form-control">
    <option data-th-value="available" data-th-text="Available"></option>
    <option data-th-value="broken" data-th-text="Broken"></option>
    <option data-th-value="not mounted" data-th-text="|Not Mounted|"></option>
  </select>
</div>

方案3:使用国际化消息(适合多语言场景)

如果你的项目需要支持多语言,可以把文本放到国际化配置文件中,通过消息表达式引用:

  1. 在messages.properties中添加:
status.not.mounted=Not Mounted
  1. 在模板中引用:
<div class="form-group">
  <label for="status">Status:</label>
  <select data-th-field="*{status}" id="status" class="form-control">
    <option data-th-value="available" data-th-text="Available"></option>
    <option data-th-value="broken" data-th-text="Broken"></option>
    <option data-th-value="not mounted" data-th-text="#{status.not.mounted}"></option>
  </select>
</div>

前两种方案完全能解决你当前的问题,方案3更适合有国际化需求的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:52:16