In my Spring Boot application, I need to process a single Thymeleaf Fragment to get its rendered HTML output.
I'm injecting
@Autowired
private SpringTemplateEngine templateEngine;
and then try to
Context context = new Context();
context.setVariable("key", value);
String html = this.templateEngine.process("fragments/foo :: bar(key=${key})", context);
with foo.html located in src/main/resources/templates/fragments:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head></head>
<body>
...
<th:block th:fragment="bar(key)">
<!-- doing fancy stuff with key... -->
</th:block>
...
</body>
</html>
I didn't change any autoconfigured values of Thymeleaf.
Running this code, I get the following exception:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "fragments/foo :: bar(key=${key})", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:924) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:898) ~[thymeleaf-2.1.4.RELEASE.jar:2.1.4.RELEASE]
...
Am I doing anything wrong here? The whole stuff gets working if I create a file src/main/resources/templates/fragments/test.html with simply the content
<div th:replace="fragments/foo :: bar(key=${key})"></div>
and process it via
String html = this.templateEngine.process("fragments/test", context);
That would be a possible solution, but seems a bit hackish to me...