一 常用指令
1. assign: 自定義變量
2. if else :流程判斷指令
3. list: 變量sequence
4. marco: 宏指令(自定義方法)
5. import: 引入命名空間
6. include: 嵌入文件指令
二 指令詳解
【1. assign 指令】: 自定義變量
1.1 自定義變量:
<#assign hw = "hello,world"/>
1.2 調(diào)用:用$ 調(diào)用
hw = ${hw}
【2. if 指令】: 判斷語句, if 相關(guān)的指令中不需要用 $ 號(hào),直接可以從map 中獲取元素
2.1 if else 組合:
<#if status == 0>
status is 0
<#else>
status is not 0
</#if>
2.2 if elseif else 組合:
<#if status ==0 >
status = 0
<#elseif status ==1>
status = 1
<#else>
status != 0 && status !=1
</#if>
【3. list 指令】:list可以遍歷sequence 類型的數(shù)據(jù), 即 數(shù)組, List, Set
1.1 foreach:
<#list citys as city>
${city_index} --> ${city}
</#list>
3.2 獲取遍歷索引: 變量名_index
<#list names as name>
${name_index} --> ${name}
</#list>
【4. macro 宏指令】, 類似于自定義方法
1. 定義宏指令(定義方法)
<#macro sayHello name1 name2>
hello, ${name1} and ${name2}
</#macro>
2. 調(diào)用宏指令(調(diào)用方法)
<@sayHello name1="zhangsan" name2="lisi"/>
3. nested 指令: 代替調(diào)用宏指令時(shí)標(biāo)簽對(duì)之間包裹的內(nèi)容
<#macro hw>
hello,<#nested>
</#macro>
<@hw>zhangsan,lisi,wangwu,zhaoliu</@hw>
【5. import 指令】: 引入命名空間:
1. 引入命名空間:<#import "templateUtil.ftl" as util />
2. 調(diào)用響應(yīng)方法:<@util.printEmp employee/>
3. 調(diào)用變量:${util.fileName}
修改變量:<#assign fileName = "command.ftl" in util />
${util.fileName}
【6. include 】嵌入文件:
1. 執(zhí)行步驟:
1. 合并文件: 將被嵌入的文件的內(nèi)容全部導(dǎo)入當(dāng)前 文件
2. 解析: 然后用freemarker 語法解析嵌入的文件片段
2. 示例:以下是文件 hello.ftl 的文本內(nèi)容:
<#include "include.txt" />
三 測(cè)試結(jié)果:
[html] view plain copy
二 指令詳解
【1. assign 指令】: 自定義變量
1.1 自定義變量:
<#assign hw = "hello,world"/>
1.2 調(diào)用:用$ 調(diào)用
hw = ${hw}
【2. if 指令】: 判斷語句, if 相關(guān)的指令中不需要用 $ 號(hào),直接可以從map 中獲取元素
2.1 if else 組合:
<#if status == 0>
status is 0
<#else>
status is not 0
</#if>
2.2 if elseif else 組合:
<#if status ==0 >
status = 0
<#elseif status ==1>
status = 1
<#else>
status != 0 && status !=1
</#if>
【3. list 指令】:list可以遍歷sequence 類型的數(shù)據(jù), 即 數(shù)組, List, Set
1.1 foreach:
<#list citys as city>
${city_index} --> ${city}
</#list>
3.2 獲取遍歷索引: 變量名_index
<#list names as name>
${name_index} --> ${name}
</#list>
【4. macro 宏指令】, 類似于自定義方法
1. 定義宏指令(定義方法)
<#macro sayHello name1 name2>
hello, ${name1} and ${name2}
</#macro>
2. 調(diào)用宏指令(調(diào)用方法)
<@sayHello name1="zhangsan" name2="lisi"/>
3. nested 指令: 代替調(diào)用宏指令時(shí)標(biāo)簽對(duì)之間包裹的內(nèi)容
<#macro hw>
hello,<#nested>
</#macro>
<@hw>zhangsan,lisi,wangwu,zhaoliu</@hw>
【5. import 指令】: 引入命名空間:
1. 引入命名空間:<#import "templateUtil.ftl" as util />
2. 調(diào)用響應(yīng)方法:<@util.printEmp employee/>
3. 調(diào)用變量:${util.fileName}
修改變量:<#assign fileName = "command.ftl" in util />
${util.fileName}
【6. include 】嵌入文件:
1. 執(zhí)行步驟:
1. 合并文件: 將被嵌入的文件的內(nèi)容全部導(dǎo)入當(dāng)前 文件
2. 解析: 然后用freemarker 語法解析嵌入的文件片段
2. 示例:以下是文件 hello.ftl 的文本內(nèi)容:
<#include "include.txt" />