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

如何在Thymeleaf中使用内部标签?实现非空内容的正确展示

Thymeleaf 正确实现方案

你错误地把th:if属性嵌套进了th:text的表达式中,这违反了Thymeleaf的语法规则,导致代码无法正常解析。以下是两种符合需求的正确实现方式:

方式一:控制<li>元素的显示(推荐)

当ingredient.amount不为null时,才渲染整个<li>标签,并拼接显示对应内容:

<ul>
  <li th:if="${ingredient.amount != null}" 
      th:text="${ingredient.amount + ' ' + ingredient.uom.description}"></li>
</ul>

方式二:保留<li>标签,动态显示内容

如果需要始终保留<li>标签,仅在amount为null时显示空内容,可以使用三元表达式:

<ul>
  <li th:text="${ingredient.amount != null ? (ingredient.amount + ' ' + ingredient.uom.description) : ''}"></li>
</ul>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:57:37