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

Thymeleaf表达式中使用变量报错,如何动态生成递增子串列表?

问题翻译

我希望在Thymeleaf中,根据模型传入的字符串生成递增的子串列表。例如输入字符串Wine时,输出如下:

W
Wi
Win
Wine

我编写了如下代码:

<h1 th:with="len=${#strings.length(name)}" th:each="i : ${#numbers.sequence(1, ${len})}" th:text="${#strings.substring(name, 0, i)}"></h1>

但无法正常运行。将${#numbers.sequence(1, ${len})}改为${#numbers.sequence(1, 4)}后可正常工作,但这样无法适配字符串长度变化。我尝试使用messages.msg()方法也无效。报错信息如下:

An error happened during template parsing (template: "class path resource [templates/name-list.html]")
Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "#numbers.sequence(1, ${len})" (template: "name-list" - line 7, col 53)

请问我哪里出错了?

解决方案

你的问题出在SpringEL表达式中错误嵌套了${}语法。

在Thymeleaf的${}表达式内部,已经处于SpringEL的上下文环境中,直接引用变量名即可,不需要再用${}包裹。你写的${#numbers.sequence(1, ${len})}里,第二个参数${len}是多余的嵌套,这会导致SpringEL解析失败。

修正后的代码如下:

<h1 th:with="len=${#strings.length(name)}" th:each="i : ${#numbers.sequence(1, len)}" th:text="${#strings.substring(name, 0, i)}"></h1>

验证说明

  • th:with="len=${#strings.length(name)}":正确计算传入字符串name的长度,存入变量len
  • ${#numbers.sequence(1, len)}:直接使用变量len作为序列的结束值,生成从1到字符串长度的整数序列
  • th:text="${#strings.substring(name, 0, i)}":循环截取字符串从0到当前索引i的子串,生成你需要的递增子串列表

这样修改后,代码就能根据传入字符串的长度动态生成对应的子串列表,适配不同长度的输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:15:31