Thymeleaf + Spring 3 th:field in Fragements

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

Thymeleaf + Spring 3 th:field in Fragements

alkos333
As per section 7.2 on http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html:

"Values for th:field attributes must be selection expressions (*{...}), which makes sense given the fact that they will be evaluated on the form-backing bean and not on the context variables (or model attributes in Spring MVC jargon)."


That is true except when peaces of form are turned into tile fragments using thymeleaf-extras-tiles2. In this case, the fragment expressions could assume the attribute names to always be the same across forms and the parent would take care of aliasing them to match the fragment expectations. So the hosting template which wants to re-use a tags fragment, could look like so:

<div th:with="tags=${anyFormBackingBean.tags}"><div tiles:replace="tags"></div></div>

In this case, within the fragment one has to use a variable expression starting with $ because we're trying to reference an aliased local variable, yet th:field prohibits that and requires a selection expression.

Of course one can just dump th:field and manually assign th:value th:name th:id and re-use the form fragment that way, but this is something th:field would have taken care of.

What is the suggested approach in this case?

Reply | Threaded
Open this post in threaded view
|

Re: Thymeleaf + Spring 3 th:field in Fragements

Antibrumm
One way of doing that can be to give the attribute name/path as a "with" expression into the fragment as you would do it for other values.
Within the fragment you use a pre-evaluation inside the selection expression.

th:field="*{__${someAttributePath}}"

This way you can build what i called "editortemplates", which handle layout, validation and error processing.
Reply | Threaded
Open this post in threaded view
|

Re: Thymeleaf + Spring 3 th:field in Fragements

maxxyme
Antibrumm wrote
th:field="*{__${someAttributePath}}"

This way you can build what i called "editortemplates", which handle layout,
validation and error processing.
Sorry to bump this thread but the solution is (notice the extra underscores) :

th:field="*{__${someAttributePath}__}"

...otherwise it doesn't work (well actually in Nov. 2016 with Thymeleaf 3.0.x)