We are developing a project under Spring 3.0 and Thymeleaf where all of the templates are in files, but we need to combine them dynamically into a form determined at render time; e.g., we get information at render time should the label be before or after each input, and how many inputs.
If it is not forms that we construct this way, we can use the StringTemplateResolver to do recursive resolving of the fragments. But with the form, we run into a problem with the inputs, since th:field will not bind to a th:object that is not yet defined (because it is in a parent template). Specifically we see something like the following:
org.thymeleaf.exceptions.TemplateProcessingException: Cannot process attribute '{th:field,data-th-field}': no associated BindStatus could be found for the intended form binding operations. This can be due to the lack of a proper management of the Spring RequestContext, which is usually done through the ThymeleafView or ThymeleafReactiveView (template: "<input th:attr="type=${type}" class="form-control" th:field="*{fields['__${name}__']}" />
We would like to avoid bypassing bind if possible (as done in How to set thymeleaf th:field value from other variable).
Our form object is called FieldMap, with a single field "fields" which is Map<String, Object> for capturing the values.
If the entire template is set up statically in the file ahead of time, it works fine, but it does not meet the requirements of our project to set it up dynamically.
Based on Process single Thymeleaf fragment with Spring Boot we tried to resolve the fragment manually, but then we got an error:
Fragment:
<html xmlns:th="http://www.thymeleaf.org">
<body>
<label th:fragment="form-element-label" th:attr="for=*{fields['__${name}__']}">[[${title}]]</label>
</body>
</html>
Parent fragment:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="form-element" class="form-group">
<div th:insert="form-element-label : form-element-label"></div>
<div th:insert="input : input"></div>
</div>
</body>
</html>
The error:
Invalid syntax in selector "/body>
</html>": selector does not match selector syntax: ((/|//)?selector)?([@attrib="value" ((and|or) @attrib2="value")?])?([index])?
Does anyone have experience (success) trying to do something like this?
We did some digging around and learned that Faces 4.0 supports views written in Java, which is a much better solution for such questions than hacking templates. Thymeleaf is a template solution, where as Faces really is not.
A very nice example or programmatic Faces views is posted here: https://hantsy.github.io/jakartaee10-sandbox/faces/faces/ and about integration with Spring (we are not ready to throw Spring out of the project in favour of full jakarta namespace) here: https://habr.com/ru/articles/736474/