如何用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
相关产品推荐
相关产品推荐

