Freemarker List排序并遍历

前言

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值