Question

Is there a way to use a fragment parameter in an expression?

I'd like to create a fragment to show fields with their corresponding binding errors e.g. like:

<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>

Getting the fragment with:

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

How do I use the field parameter in the expressions for the th:field and th:errors attributes? *{field} does at least not work.

Was it helpful?

Solution

With Thymeleaf 2.1 I've been using the following:

Declare field:

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

Show possible errors related to password:

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

And this prints all the errors related to given field:

<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>

OTHER TIPS

It seems that it is not possible at least using th:field and th:errors, it keeps trying to look for a bean instead of the parameter of the fragment.

Try setting a local variable for the DOM object

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

An then try to use that variable in the expressions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top