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

Thymeleaf是否支持使用动态拼接生成的model属性名称?

你给出的写法Thymeleaf并不支持,核心问题是${}表达式不允许嵌套使用,你要实现动态拼接变量名获取model属性的需求,可以用以下两种合法方案:

  • 方案1:使用Thymeleaf内置上下文对象#ctx直接读取变量
    该方案语法直观,不需要额外理解预处理机制,推荐优先使用:
    <p th:if="${#ctx.getVariable('somePrefix_' + entry.key)} != null">Write if condition is met.</p>
    
  • 方案2:使用Thymeleaf预处理语法
    用双下划线__包裹的表达式会先执行计算得到最终的变量名,再交由外层${}解析:
    <p th:if="${__${'somePrefix_' + entry.key}__} != null">Write if condition is met.</p>
    

如果你的变量仅存于请求作用域,也可以用#httpServletRequest.getAttribute('somePrefix_' + entry.key)来读取,效果和#ctx.getVariable一致。

内容的提问来源于stack exchange,提问作者Leon Fadljević

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:18:03