Reputation: 11818
I have an Spring Boot (2M6) application which is using Thymeleaf to render some HTML documents.
My templates include some fragments which are ultimately selected based on user input. On some occasions the user input results in selection of a fragment that does not exist.
This is an error, and currently this results in an exception and the template does not render. I would like to either render a different, default "invalid selection" fragment, or perhaps even an empty fragment.
The top end of the stack trace looks like this
org.thymeleaf.exceptions.TemplateInputException: Error resolving fragment: ":: ${entity.fields[code]}": template or fragment could not be resolved (template: "common/fragments" - line 5, col 14)
at org.thymeleaf.standard.processor.AbstractStandardFragmentInsertionTagProcessor.doProcess(AbstractStandardFragmentInsertionTagProcessor.java:117) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleStandaloneElement(ProcessorTemplateHandler.java:918) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.StandaloneElementTag.beHandled(StandaloneElementTag.java:228) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
at org.thymeleaf.engine.Model.process(Model.java:282) ~[thymeleaf-3.0.8.RELEASE.jar:3.0.8.RELEASE]
If entity.fields[code]
contains a value for which there is a matching th:fragment
, all is well.
Working back from AbstractStandardFragmentInsertionTagProcessor.doProcess
AbstractStandardFragmentInsertionTagProcessor#computeFragment seems to, by choice, always fail if the fragment does not exist.
This seems to be contrary to another answer. FWIW I've tried using th:include
, th:insert
and th:replace
Is it possible to detect if a fragment is defined (so that I can then select a different fragment)? Or alternatively, what tools are available to handle missing fragments and where are the levers to adjust them?
I'm pretty new to Thymeleaf, so I've probably missed something fairly basic.
Upvotes: 1
Views: 1345
Reputation: 11818
As is always the way, I spot something after submitting the question.
The documentation for advanced conditional insertion of fragments includes an example of what I'm trying to achieve
My fragment insertion now looks like
<div th:replace="~{:: __${entity.fields[code]}__} ?: _">
Invalid code
</div>
Upvotes: 1