pom.xml
<!-- beetl模板引擎 --><dependency><groupId>com.ibeetl</groupId><artifactId>beetl-core</artifactId><version>3.19.1.RELEASE</version></dependency>
BeetlUtils
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;/*** Beetl工具类*/
public final class BeetlUtils {private BeetlUtils() { };private static GroupTemplate groupTemplate;private static Object block = new Object();/*** 以懒汉模式获取 GroupTemplate 对象* @return GroupTemplate*/public static GroupTemplate getGroupTemplate() {if (groupTemplate == null) {synchronized (block) {if (groupTemplate == null) {try {ClasspathResourceLoader webAppResourceLoader = new ClasspathResourceLoader("/");Configuration config = Configuration.defaultConfiguration();// Beetl的核心GroupTemplategroupTemplate = new GroupTemplate(webAppResourceLoader, config);} catch (IOException e) {e.printStackTrace();}}}}return groupTemplate;}/*** 创建新文件* @param map 参数* @param templatePath 模板路径* @param storePath 存储路径*/public static void createFile(Map<String, Object> map, String templatePath, String storePath) {OutputStream out = null;try {File file = new File(storePath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}if (!file.exists()) {file.createNewFile();}GroupTemplate groupTemplate = BeetlUtils.getGroupTemplate();Template template = groupTemplate.getTemplate(templatePath);template.fastBinding(map);out = new FileOutputStream(storePath);template.renderTo(out);} catch (IOException e) {e.printStackTrace();} finally {if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 创建HTML字符串* @param map 参数* @param templatePath 模板路径*/public static String createHTML(Map<String, Object> map, String templatePath) {GroupTemplate groupTemplate = BeetlUtils.getGroupTemplate();Template template = groupTemplate.getTemplate(templatePath);template.fastBinding(map);// 渲染字符串return template.render();}public static void main(String[] args) {Map<String, Object> map = new HashMap<>();map.put("title", "This is a test template Email.");map.put("body", "Hello, beetl!");String html = createHTML(map, "/template/hello.html.btl");System.out.println(html);}
}
hello.html.btl
<!-- beetl示例 -->
<html><head> <title>${title}</title> </head> <body> <h1>${body}</h1> </body>
</html>
运行
<!-- beetl示例 -->
<html><head> <title>This is a test template Email.</title> </head> <body> <h1>Hello, beetl!</h1> </body>
</html>