Thymeleaf 是新一代的Java模板引擎,它的語法對前端開發者友好可直接打開編輯,Spring Boot也建議使用它作為你的模板引擎,本文將演示如何使用它提供的API來渲染模板生成靜態頁面。
引入Maven依賴
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
創建模板,templates/example.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${name}">列表名稱</h1>
<ul>
<li th:each="item: ${array}" th:text="${item}">條目</li>
</ul>
</body>
</html>
使用API渲染模板生成靜態頁面
//構造模板引擎
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/");//模板所在目錄,相對于當前classloader的classpath。
resolver.setSuffix(".html");//模板文件后綴
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
//構造上下文(Model)
Context context = new Context();
context.setVariable("name", "蔬菜列表");
context.setVariable("array", new String[]{"土豆", "番茄", "白菜", "芹菜"});
//渲染模板
FileWriter write = new FileWriter("result.html");
templateEngine.process("example", context, write);
執行上述代碼查看生成結果,result.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>蔬菜列表</h1>
<ul>
<li>土豆</li>
<li>番茄</li>
<li>白菜</li>
<li>芹菜</li>
</ul>
</body>
</html>