最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

spring mvc - Correct way to pass a form value to a Thymeleaf fragment to link label and field correctly - Stack Overflow

programmeradmin4浏览0评论

Working on thymeleaf I found this behaviour that is causing me some trouble to correctly link togheter a form field and a label.

I use to template anytime I can, so my forms are usually composed by a lot of nested fragments in order to reuse as much as I can.

Here's an example:

A textarea fragment

<th:block th:insert="~{components/form-generic-components :: input-textarea(label = 'Notes', dto = '__${dtoPrefix}__.notes')}"/>

which is formed by

    <th:block th:fragment="input-textarea(label, dto)">
        <th:block th:insert="~{components/form-generic-components :: label-element(text = ${label}, dto = ${dto})}" />
        <textarea class="form-control" rows="2" th:field="*{__${dto}__}"></textarea>
    </th:block>

which contains

<th:block th:fragment="label-element(text, dto)">
    <th:block th:if="${not #strings.isEmpty(text)}">
        <label th:for="|${dto}|" class="form-label text-dark fw-bold" th:text="|${#strings.capitalize(text)}|"></label>
        <span class="ps-3 form-text text-danger" th:if="${#fields.hasErrors('__${dto}__')}" th:id="${dto} + |_error|" th:errors = "*{__${dto}__}"></span>
    </th:block>
</th:block>

Everything works fine except when I pass a nested list property to the template. It seems that the same value used to th:for in label and th:field/th:id/th:value into input field are rendered differently.

Example:

<label for="elencoEdizioni[0].elencoVolumi[0].note" class="form-label text-dark fw-bold">Note</label>
<textarea class="form-control" rows="2" id="elencoEdizioni0.elencoVolumi0.note" name="elencoEdizioni[0].elencoVolumi[0].note" data-np-intersection-state="visible"></textarea>

As you can see label's for attribute equals to textarea's name attribute but both are different (no square brackets) from textarea's id attribute, which prevents the correct associacion between label and it's field.

Those three attributes are generated from the same value. The problem seems to be the square brackets, because if I pass a simple 'object.property' string it works fine.

Am I missing something? Do you have any ideas to solve the issue?

Many thanks

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论