如何获取Thymeleaf中的html内容?

问题描述

我在SpringBoot中打算写一个邮件模板,在模板中替换变化的参数,转换为 html 字符串,再传给邮件服务。但是在获取html字符串的时候,结果在预期之外

问题出现的环境背景及自己尝试过哪些方法

这是我在学习SpringBoot的邮件服务遇到的问题,参考文章是Spring Boot (十):邮件服务

相关代码

resource/templates/emailTemplate.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    你好,<span th:text="${username}"></span>!
</body>
</html>
@Test
    public void testThymeleaf() {
        Context context = new Context();
        context.setVariable("username", "wedjg");
        String result = templateEngine.process("emailTemplate", context);
        System.out.println(result);
    }

你期待的结果是什么?实际看到的错误信息又是什么?

预期的结果是输出被渲染后的html字符串,也就是:<html>...</html>;
但是实际返回的结果却是"emailTemplate"

请问我该如何做才能获取到html字符串?

阅读 7.9k
3 个回答

String result = templateEngine.process("emailTemplate", context);

第一个参数不应该是"emailTemplate", 而应该是对应模板的内容, 改成

File file = ResourceUtils.getFile("classpath:template/emailTemplate.html");
String result = templateEngine.process(new String(Files.readAllBytes(file.toPath())),context);
新手上路,请多包涵

刚好碰到跟楼主相同的问题,如果是采用springboot默认配置的话

@Autowired
private TemplateEngine templateEngine;

@Test
    public void testThymeleaf() {
        Context context = new Context();
        context.setVariable("username", "wedjg");
        String result = templateEngine.process("emailTemplate", context);
        System.out.println(result);
    }

直接使用注入的TemplateEngine对象就能直接访问到resource/templates目录下的模板文件

新手上路,请多包涵

同样问题,需要使用springboot-start的依赖。直接使用thymeleaf依赖是这样的。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题