目录
资料
引入依赖
<dependencies>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.1.0.M1</version>
</dependency>
</dependencies>
定义模板
以html为例
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span th:text="${username}"></span>
</body>
</html>
使用
以下测试代码分别演示了输出到变量和流的情况,更多用法可以参考官网或源代码
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class ThymeleafDemo {
public static void main(String[] args) throws IOException {
// 定义、设置模板解析器
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
// 设置模板类型 # https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#what-is-thymeleaf
// HTML、XML、TEXT、JAVASCRIPT、CSS、RAW
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setPrefix("/template/");
templateResolver.setSuffix(".html");
// 定义模板引擎
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
// 定义数据模型
Context context = new Context();
context.setVariable("username","张三");
// 渲染模板 (输出到变量(控制台))
System.out.println(templateEngine.process("test", context));
// 输出到流(文件)
File file = new File("E:\\","test_out.html");
Writer write = new FileWriter(file);
templateEngine.process("test",context,write);
}
}