1. 程式人生 > >freemarker建立模板檔案&常用指令&內建函式

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!""}