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

Thymeleaf模板报错:Could not parse as expression问题求助

问题排查与解决:Thymeleaf th:class解析错误

错误原因

使用th:class属性时,Thymeleaf会将属性值视为OGNL/Spring EL表达式解析。你传入的"header-wrapper header_fixed bg_transparent"包含空格,Thymeleaf会把空格当作表达式分隔符,尝试解析为多个表达式,违反语法规则,因此抛出解析异常。


解决方案

根据你的需求选择对应写法:

情况1:仅设置静态CSS类(无动态逻辑)

  • 写法一:用单引号包裹类名字符串,作为字面量表达式传递:
<header th:class="'header-wrapper header_fixed bg_transparent'" id="header-wrapper">
  • 写法二:直接使用原生class属性(和你最初正常运行的模板一致):
<header class="header-wrapper header_fixed bg_transparent" id="header-wrapper">

情况2:需要动态添加/修改类

如果后续要结合条件逻辑动态控制类名,推荐以下方式:

  • 追加静态类:使用th:classappend
<header class="header-wrapper header_fixed" th:classappend="bg_transparent" id="header-wrapper">
  • 拼接静态与动态类:使用Thymeleaf字面量替换语法(|...|)
<header th:class="|header-wrapper header_fixed ${isTransparent ? 'bg_transparent' : 'bg_opaque'}|" id="header-wrapper">

内容的提问来源于stack exchange,提问作者Nunyet Calçada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:21:05