Thymeleaf错误消息优化

时间:2016-06-14 17:54:54

标签: spring-mvc error-handling thymeleaf

我查看了本教程:https://spring.io/guides/gs/validating-form-input

使用th:errors会导致出现<br> separeted错误消息。我想要一个无序列表。所以我已经定义了这样一个片段......

<td th:fragment="validationMessages(field)" th:if="${#fields != null and field != null and #fields.hasErrors(field)}">
    <ul>
        <li th:each="error : ${#fields.errors(field)}" th:text="${error}"></li>
    </ul>
</td>

......并将其用于......

<td th:replace ="form :: validationMessages('age')"></td>

是否有“干净代码”解决方案/最佳做法,例如覆盖th:errors的呈现实现?

1 个答案:

答案 0 :(得分:1)

您可能会创建自己的Thymeleaf处理器,基于org.thymeleaf.spring4.processor.attr.SpringErrorsAttrProcessor,使用您自己的分隔错误的方法,然后使用它而不是Thymeleaf给您的那个。但它看起来并不是特别适合扩展。

我认为你这样做的方式可能是最好的。我倾向于喜欢我的HTML模板使用模板语言(如Thymeleaf)而不是Java代码。您可以根据需要进行修改(例如添加样式类),并清楚代码的作用。这正是为模板片段制作的那种东西。

相关问题