java - 使用 Spring Boot 处理单个 Thymeleaf 片段

标签 java spring-boot thymeleaf

在我的 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/

相关文章:

使用 thymeleaf 的 Java spring-boot 登录示例代码

java - java中比较两个字符串以忽略大小写和特殊字符?

java - setLong 方法参数与数据类型不匹配

带有 H2 控制台的 spring-boot-legacy

java - spring boot 从不同的 maven 模块读取属性文件

java - Jpa 存储库 findBy 方法签名具有多个 or 运算符?

java - 使用 Drools 以结构松散的 JSON 实体形式处理事实的优雅方法?

java - 与 IBM MQ 的客户端连接未经授权

javascript - 将变量从 thymeleaf 传递给 javascript 函数?

java - 如何将随机数从Java类传递到html文件