前言
FreeMarker 是一款模板引擎: 基于模板填充数据, 可以用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。
使用它的好处在于,我们可以动态改变模板来达到动态改内容的效果,避免去修改Java代码。
下面的案例是演示如何通过freemarker模板,来实现List集合的遍历和排序。
freemarker模板配置
倒序排列:<#list 集合?sort_by(["排序字段"])?reverse >
<html>
<head></head>
<body>
<table class="tftable">
<tr><th colspan=4>Product by ${domain}</th></tr>
<tr><th>产品</th><th>价格</th><th>数量</th></tr>
<#list products?sort_by(["price"])?reverse >
<#items as p>
<tr><td>${p.name}</td><td>${p.price}</td><td>${p.num}</td></tr>
</#items>
</#list>
</table>
<p><small>系统自动发送,请勿回复!</small></p>
</body>
</html>
数据模型
public Map<String,Object> dataModel(){
Map<String, Object> root = new HashMap<>();
root.put("domain", "3C");
List<Map<String,Object>> products = new ArrayList<>();
root.put("products", products);
for (int i = 1; i <= 3; i++) {
Map<String, Object> map = new HashMap<>(2);
map.put("name", "MEIZU 20Pro"+i);
map.put("price", i+899);
map.put("num", RandomStringUtils.randomNumeric(5));
products.add(map);
}
return root;
}
freemarker配置
private static Configuration cfg;
@PostConstruct
private void init() {
cfg = new Configuration(Configuration.VERSION_2_3_31);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateLoader(new StringTemplateLoader());
}
@Test
public void test() throws Exception{
// 读取freemarker模板
File tempFile = new File(FileSystemView.getFileSystemView().getHomeDirectory() + "/Desktop/test.ftl");
// 读到字符串中
String tempStr = FileUtils.readFileToString(tempFile, StandardCharsets.UTF_8);
// 生成测试数据
dataModel();
// 创建freemarker模板对象
Template temp = new Template("template",new StringReader(tempStr), cfg, "UTF-8");
StringWriter out = new StringWriter();
temp.process(rootMap, out);
out.flush();
String result = out.toString();
// 打印填充后的内容
System.out.println("result = " + result);
}
运行结果
官方中文手册:http://freemarker.foofun.cn/index.html