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

如何用Thymeleaf根据条件完全移除a标签的href属性?

在Thymeleaf中根据条件移除a标签的href属性

你可以通过以下两种非JavaScript的Thymeleaf实现方式,完全移除不符合条件时的href属性:

方法一:动态设置属性(简洁版)

利用th:attr根据条件动态添加href属性,不满足条件时不会生成该属性:

<a th:attr="${canUpdatePassword} ? href=@{/password/update} : ''">Forgot password?</a>

方法二:拆分标签渲染(直观版)

通过th:if和th:unless分别渲染两种状态的a标签,彻底避免属性残留:

<a th:if="${canUpdatePassword}" th:href="@{/password/update}">Forgot password?</a>
<a th:unless="${canUpdatePassword}">Forgot password?</a>

第一种方法无需重复编写标签内容,适合简单场景;第二种方法逻辑更直白,便于维护复杂业务规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 17:27:04