在我的 Spring Boot 应用程序中,我需要处理单个 Thymeleaf 片段以获取其呈现的 HTML 输出。
我在注入(inject)
@Autowired
private SpringTemplateEngine templateEngine;
然后尝试
Context context = new Context();
context.setVariable("key", value);
String html = this.templateEngine.process("fragments/foo :: bar(key=${key})", context);
foo.html
位于 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>
我没有更改 Thymeleaf 的任何自动配置值。
运行这段代码,我得到以下异常:
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]
...
我是不是做错了什么?如果我创建一个只包含内容的文件 src/main/resources/templates/fragments/test.html
<div th:replace="fragments/foo :: bar(key=${key})"></div>
并通过
处理String html = this.templateEngine.process("fragments/test", context);
这将是一个可能的解决方案,但对我来说似乎有点老套......
最佳答案
Ken 的答案有效,但我用更简单的方法做到了:
templateEngine.process("nameTemplate", context, new DOMSelectorFragmentSpec("DOM selector"));
还有其他方法可以过滤处理过的模板,记录在案here
关于java - 使用 Spring Boot 处理单个 Thymeleaf 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36042748/