Thymeleaf结合Spring时th:errors行为不符文档描述的问题咨询
Thymeleaf th:errors 导致元素被移除的问题
在Thymeleaf与Spring结合使用时,会提供如th:errors这类扩展属性。根据官方文档,可以通过以下方式获取字段错误信息:
<input type="text" th:field="*{datePlanted}" /> <p th:if="${#fields.hasErrors('datePlanted')}" th:errors="*{datePlanted}">Incorrect date</p>
因此我在自己的应用中为密码输入框改写了这段代码:
<input id="password" type="password" name="password" th:field="*{password}"/> <p class="error-message" th:classappend="${#fields.hasErrors('password')} ? _ : 'hidden'" th:errors="*{password}">Invalid password</p>
由于我不希望错误提示段落在预处理时被移除,所以通过th:classappend根据是否存在错误来添加hidden类,以便前端JavaScript可以操作该段落。
但遗憾的是,尽管我完全按照文档实现,无错误时该段落仍被删除。看起来th:errors属性似乎默认实现了th:if的逻辑,会检查是否存在错误,若无错误则完全不显示该段落。
而文档示例中是通过th:if显式控制段落是否显示,因此我无法理解这种行为。
请问这是bug、特性还是我自身的问题?
这是Thymeleaf的特性,不是bug也不是你的问题。
th:errors属性本身就自带条件渲染逻辑:当目标字段没有错误时,它会直接移除所在的整个元素,不管你有没有用th:classappend或者其他属性。官方文档里的示例用th:if其实是一种冗余写法——即使去掉th:if,th:errors也会自动隐藏无错误的元素,文档这么写只是为了更清晰地展示判断逻辑。
如果想保留元素只是隐藏它,不要用th:errors,可以改用th:text结合#fields.hasErrors()和#fields.errors()来手动控制:
<p class="error-message" th:classappend="${#fields.hasErrors('password')} ? '' : 'hidden'" th:text="${#fields.hasErrors('password')} ? ${#fields.errors('password')[0]} : 'Invalid password'"> Invalid password </p>
或者更简洁的写法,利用三元表达式直接处理样式和内容:
<p class="error-message" th:class="${#fields.hasErrors('password')} ? 'error-message' : 'error-message hidden'" th:text="${#fields.errors('password')} ?: 'Invalid password'"> Invalid password </p>
这样就能保证段落始终存在,只是通过hidden类控制显示状态,同时正确展示错误信息。
内容的提问来源于stack exchange,提问作者Slevin
相关产品推荐
相关产品推荐

