freemarker创建模板文件&常用指令&内建函数

一:引入freemarker坐标:

<dependency>

<groupId>org.freemarker</groupId>

<artifactId>freemarker</artifactId>

<version>2.3.23</version>

</dependency>

二:创建模板文件test.ftl

<html>

<head>

<meta charset="utf-8">

<title>Freemarker入门小DEMO </title>

</head>

<body>

<#--我只是一个注释,我不会有任何输出 -->

${name},你好。${message}

</body>

</html>

三:加载模板,创建文件

//1.创建配置类

Configuration configuration=new Configuration(Configuration.getVersion());

//2.设置模板所在的目录

configuration.setDirectoryForTemplateLoading(new File("D:/pyg_work/freemarkerDemo/src/main/resources/"));

//3.设置字符集

configuration.setDefaultEncoding("utf-8");

//4.加载模板

Template template = configuration.getTemplate("test.ftl");

//5.创建数据模型

Map map=new HashMap();

map.put("name", "张三 ");

map.put("message", "欢迎来到神奇世界!");

//6.创建Writer对象

Writer out =new FileWriter(new File("d:\\test.html"));

//7.输出

template.process(map, out);

//8.关闭Writer对象

out.close();

四:模板指令(ftl指令)

1)assign指令

<#assign linkman="周先生">

联系人:${linkman}

<#assign info={"mobile":"13301231212",'address':'北京市昌平区王府街'} >

电话:${info.mobile} 地址:${info.address}

2)include指令

<#include "head.ftl">

3)if指令

<#if success=true>

你已通过实名认证

<#else>

你未通过实名认证

</#if>

4)list指令

<#list goodsList as goods>

${goods_index+1} 商品名称: ${goods.name} 价格:${goods.price}<br>

</#list>

如果想在循环中得到索引,使用循环变量+_index就可以得到。

五:内建函数

语法:变量+?+函数名称

1)获取集合大小?size

共 ${goodsList?size} 条记录

2)字符串转为json对象?eval

<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />

<#assign data=text?eval />

开户行:${data.bank} 账号:${data.account}

3)日期格式化

当前日期:${today?date} <br>

当前时间:${today?time} <br>

当前日期+时间:${today?datetime} <br>

日期格式化: ${today?string("yyyy年MM月")}

4)数字转为字符串?c

累计积分:${point?c}

5)判断变量是否存在:“??”

<#if aaa??>

aaa变量存在

<#else>

aaa变量不存在

</#if>

6)变量不存在赋值默认值为""

${aaa!""}

猜你喜欢

转载自blog.csdn.net/qq_15076569/article/details/83476761