Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf: How to use fragment parameter in expressions

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.

like image 459
James Avatar asked Nov 30 '25 20:11

James


1 Answers

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>
like image 90
perak Avatar answered Dec 03 '25 11:12

perak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!