【问题标题】:Thymeleaf: How to use fragment parameter in expressionsThymeleaf:如何在表达式中使用片段参数
【发布时间】:2014-02-28 15:14:46
【问题描述】:

有没有办法在表达式中使用片段参数?

我想创建一个片段来显示具有相应绑定错误的字段,例如喜欢:

<div th:fragment="alert (field, fieldLabel)">
    <label><span th:text="${fieldLabel}">Label:</span><input type="text" th:errorclass="field_error" th:field="*{field}"/></label>
    <div th:if="${#fields.hasErrors(field)}"><span th:errors="*{field}">Some error</span></div>
</div>

获取片段:

<div th:replace=":: alert (field='firstName', fieldLabel='Firstname')">Field</div>

如何在 th:field 和 th:errors 属性的表达式中使用 field 参数? *{field} 至少不起作用。

【问题讨论】:

    标签: spring spring-mvc thymeleaf


    【解决方案1】:

    对于 Thymeleaf 2.1,我一直在使用以下内容:

    声明字段:

    <input type="password" th:field="*{password}" />
    

    显示可能与密码相关的错误:

    <div th:replace="util/form :: field-errors('password')"></div>
    

    这会打印出与给定字段相关的所有错误:

    <div class="error-container help-block"
            th:fragment="field-errors(field)"
            th:if="${#fields.hasErrors('__${field}__')}">
        <ul>
            <li th:each="error : ${#fields.errors('__${field}__')}"
                th:text="${error}" />
        </ul>
    </div>
    

    【讨论】:

      【解决方案2】:

      看来至少不可能 使用 th:field 和 th:errors,它一直试图寻找一个 bean 片段的参数。

      尝试为 DOM 对象设置一个局部变量

      th:with="variableName=${field}"
      

      然后尝试在表达式中使用该变量。

      【讨论】:

        猜你喜欢
        • 2018-10-07
        • 2014-04-01
        • 2017-05-20
        • 1970-01-01
        • 1970-01-01
        • 2018-06-05
        • 2015-03-20
        • 1970-01-01
        • 2020-06-02
        相关资源
        最近更新 更多