在我的Spring Boot应用程序中,我需要处理一个Thymeleaf Fragment以获取其呈现的HTML输出.
我正在注射
@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);
那将是一个可能的解决方案,但对我来说似乎有点不足.
解决方法:
SpringTemplateEngine不会解析片段.因此,模板名称不应包含片段声明.要处理片段,您必须使用另一个重载的SpringTemplateEngine.process()方法,并手动解析片段:
Context context = new Context();
context.setVariable("key", value);
ProcessingContext processingContext = new ProcessingContext(context);
StandardFragment fragmentSpec =
StandardFragmentProcessor.computeStandardFragmentSpec(templateEngine.getConfiguration(),
processingContext, "fragments/foo :: #bar", "SpringStandard", "fragment");
String html = templateEngine.process("fragments/foo",
context, fragmentSpec.getFragmentSpec());
实际上,我没有使用< th:block>片段.我的片段如下所示:
<body>
...
<div id="bar" th:remove="tag">
<!-- doing fancy stuff with key... -->
<span th:text="${key}"></span>
</div>
...
</body>
正如您所指出的,我通过#bar div的ID选择了该片段.
标签:spring-boot,thymeleaf,java 来源: https://codeday.me/bug/20191118/2031957.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。