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

如何在Thymeleaf中以th:each循环对象为参数调用函数

解决Thymeleaf调用对象方法时的SpEL解析错误

问题根源

你在Thymeleaf里调用listInvoicesForm的isParsedFileAvailable()方法时,错误地在选择表达式(*{...})内部嵌套了${}变量语法,导致SpEL解析器无法识别表达式结构,抛出EL1043E: Unexpected token错误。选择表达式本身已经基于th:object指定的上下文工作,不需要再用${}包裹方法参数。

正确写法

有两种可行的修改方式:

方式一:保持选择表达式(推荐,贴合当前代码上下文)

直接在选择表达式里传入循环变量invoiceIndex,不用额外包裹:

<table th:object="${listInvoicesForm}">
...
<tr th:each="invoiceIndex, rowStat : *{invoiceIndexes}" >
   ...
    <td align="center" width="5%">
        <span th:if="*{!isParsedFileAvailable(invoiceIndex)}" th:text="-">- (No Parsed File)</span>
    </td>
</tr>
</table>

方式二:使用变量表达式

绕过选择表达式,直接通过对象名调用方法:

<table th:object="${listInvoicesForm}">
...
<tr th:each="invoiceIndex, rowStat : *{invoiceIndexes}" >
   ...
    <td align="center" width="5%">
        <span th:if="${!listInvoicesForm.isParsedFileAvailable(invoiceIndex)}" th:text="-">- (No Parsed File)</span>
    </td>
</tr>
</table>

原理说明

  • 选择表达式*{...}会自动绑定到th:object指定的listInvoicesForm对象,方法调用会直接作用于该对象。
  • 循环变量invoiceIndex在当前<tr>的上下文里是直接可用的,无需用${}再次引用,否则会破坏SpEL的表达式结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:54:59