Set attributes dynamic

classic Classic list List threaded Threaded
6 messages Options
Reply | Threaded
Open this post in threaded view
|

Set attributes dynamic

vitornp
It would be possible to do something like:

<th:block th:replace="input" th:with="attr='maxlength=\'70\' required=\'required\'" />

<div th:fragment="input">
        <input th:type="text" th:name="test" th:id="test" th:attr="${attr}" />
</div>

Return exception
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as assignation sequence: "${attr}" (input:29)
Reply | Threaded
Open this post in threaded view
|

Re: Set attributes dynamic

Zemi
Administrator
Have you tried preprocessing?

   th:attr="__${attr}__"

Regards,
   Zemi

Reply | Threaded
Open this post in threaded view
|

Re: Set attributes dynamic

vitornp
Same error
Reply | Threaded
Open this post in threaded view
|

Re: Set attributes dynamic

danielfernandez
Administrator
In reply to this post by vitornp
th:attr expects you to specify both the name of the attribute to be set and its value, something like:

th:attr="value=${myvalue}"

Your syntax is therefore incorrect. What attribute are you trying to set?
Reply | Threaded
Open this post in threaded view
|

Re: Set attributes dynamic

danielfernandez
Administrator
Oh, I see, you try to set two attributes at once.

If you are using Thymeleaf 2.1, and assuming your "input" fragment is in the same page, I recommend you the following syntax:

<th:block th:replace="::input (maxlength=70, required=true)" />

<div th:fragment="input">
        <input th:type="text" th:name="test" th:id="test" th:maxlength="${maxlength}" th:required="${required}" />
</div>

...or even:

<th:block th:replace="::input(70,true)" />

<div th:fragment="input(maxlength,required)">
        <input th:type="text" th:name="test" th:id="test" th:maxlength="${maxlength}" th:required="${required}" />
</div>


By the way, if you are using Spring those th:name and th:id are equivalent to using just th:field.

Reply | Threaded
Open this post in threaded view
|

Re: Set attributes dynamic

vitornp
The idea was to make dynamic attributes, like in the example.

Each input would have its attributes inclusion of the fragment.