A 概念
最常用的 3 個概念
sequence 序列,對應java 裏的list 、數組等非鍵值對的集合
hash 鍵值對的集合
namespace 對一個ftl 文件的引用, 利用這個名字可以訪問到該ftl 文件的資源
B 指令
if, else, elseif
語法
- <#if condition>
- ...
- <#elseif condition2>
- ...
- <#elseif condition3>
- ...
- ...
- <#else>
- ...
- </#if>
<#if condition>
...
<#elseif condition2>
...
<#elseif condition3>
...
...
<#else>
...
</#if>
用例
- <#if x = 1>
- x is 1
- </#if>
- <#if x = 1>
- x is 1
- <#else>
- x is not 1
- </#if>
switch, case, default, break
語法
- <#switch value>
- <#case refValue1>
- ...
- <#break>
- <#case refValue2>
- ...
- <#break>
- ...
- <#case refValueN>
- ...
- <#break>
- <#default>
- ...
- </#switch>
用例
- <#switch being.size>
- <#case "small">
- This will be processed if it is small
- <#break>
- <#case "medium">
- This will be processed if it is medium
- <#break>
- <#case "large">
- This will be processed if it is large
- <#break>
- <#default>
- This will be processed if it is neither
- </#switch>
- <#switch x>
- <#case x = 1>
- 1
- <#case x = 2>
- 2
- <#default>
- d
- </#switch>
list, break
- <#list sequence as item>
- ...
- <#if item = "spring"><#break></#if>
- ...
- </#list>
關鍵字
item_index:是list當前值的下標
item_has_next:判斷list是否還有值
- <#assign seq = ["winter", "spring", "summer", "autumn"]>
- <#list seq as x>
- ${x_index + 1}. ${x}<#if x_has_next>,</#if>
- </#list>
輸出:
1.winter,
2.spring,
3.summer,
4.autumn
include
- <#include filename>
或則
- <#include filename options>
<#include filename options>
options包含兩個屬性
encoding="GBK" 編碼格式
parse=true 是否作爲ftl語法解析,默認是true,false就是以文本方式引入.注意在ftl文件里布爾值都是直接賦值
的如parse=true,而不是parse="true"
- Copyright 2001-2002 ${me}
- All rights reserved.
- <#assign me = "Juila Smith">
- Some test
- Yeah
- ___________________________________________________________________________
- <SPAN><STRONG><SPAN><#include "/common/copyright.ftl" encoding="GBK"></SPAN>
- </STRONG>
- </SPAN>
<#assign me = "Juila Smith">
Some test
Yeah
___________________________________________________________________________
<#include "/common/copyright.ftl" encoding="GBK">
Import
類似於java裏的import,它導入文件,然後就可以在當前文件裏使用被導入文件裏的宏組件
- <#import "/libs/mylib.ftl" as my>
- <@my.copyright date="1999-2002"/>
- <#-- "my"在freemarker裏被稱作namespace -->
compress
- <#compress>
- ...
- </#compress>
escape, noescape
- <#escape identifier as expression>
- ...
- <#noescape>...</#noescape>
- ...
- </#escape>
- <#escape x as x?html>
- First name: ${firstName}
- <#noescape>Last name: ${lastName}</#noescape>
- Maiden name: ${maidenName}
- </#escape>
- First name: ${firstName?html}
- Last name: ${lastName }
- Maiden name: ${maidenName?html}
assign
- <#assign name=value>
- <#-- 或則 -->
- <#assign name1=value1 name2=value2 ... nameN=valueN>
- <#-- 或則 -->
- <#assign same as above... in namespacehash>
- <#-- 或則 -->
- <#assign name>
- capture this
- </#assign>
- <#-- 或則 -->
- <#assign name in namespacehash>
- capture this
- </#assign>
- <#assign seasons = ["winter", "spring", "summer", "autumn"]>
給變量test加1
- <#assign test = test + 1>
給my namespage 賦予一個變量bgColor,下面可以通過my.bgColor來訪問這個變量
- <#import "/mylib.ftl" as my>
- <#assign bgColor="red" in my>
將一段輸出的文本作爲變量保存在x裏
- <#assign x>
- <#list 1..3 as n>
- ${n} <@myMacro />
- </#list>
- </#assign>
- Number of words: ${x?word_list?size}
- ${x}
- <#assign x>Hello ${user}!</#assign> error
- <#assign x=" Hello ${user}!"> true
同時也支持中文賦值,如:
- <#assign 語法>
- java
- </#assign>
- ${語法}
打印輸出:
java
global
- <#global name=value>
- <#--或則-->
- <#global name1=value1 name2=value2 ... nameN=valueN>
- <#--或則-->
- <#global name>
- capture this
- </#global>
setting
- <#setting name=value>
- ${1.2}
- <#setting locale="en_US">
- ${1.2}
macro, nested, return
- <#macro name param1 param2 ... paramN>
- ...
- <#nested loopvar1, loopvar2, ..., loopvarN>
- ...
- <#return>
- ...
- </#macro>
- <#macro test foo bar="Bar"[A2] baaz=-1>
- Test text, and the params: ${foo}, ${bar}, ${baaz}
- </#macro>
- <@test foo="a" bar="b" baaz=5*5-2/>
- <@test foo="a" bar="b"/>
- <@test foo="a" baaz=5*5-2/>
- <@test foo="a"/>
- <#macro list title items>
- ${title?cap_first}:
- <#list items as x>
- *${x?cap_first}
- </#list>
- </#macro>
- <@list items=["mouse", "elephant", "python"] title="Animals"/>
輸出結果:
Animals:
*Mouse
*Elephant
*Python
- <#macro repeat count>
- <#list 1..count as x>
- <#nested x, x/2, x==count>
- </#list>
- </#macro>
- <@repeat count=4 ; c halfc last>
- ${c}. ${halfc}<#if last> Last!</#if>
- </@repeat>
t, lt, rt
- <#t> 去掉左右空白和回車換行
- <#lt>去掉左邊空白和回車換行
- <#rt>去掉右邊空白和回車換行
- <#nt>取消上面的效果
- <#if mouse?exists>
- Mouse found
- <#else>
也可以直接${mouse?if_exists})輸出布爾形
--------------------------------------------
(1)解決輸出中文亂碼問題:
freemarker亂碼的原因:
- 沒有使用正確的編碼格式讀取模版文件,表現爲模版中的中文爲亂碼
解決方法:在classpath上放置一個文件freemarker.properties,在裏面寫上模版文件的編碼方式,比如
default_encoding=UTF-8
locale=zh_CN注意:eclipse中除了xml文件、java文件外,默認的文件格式iso8859-1
- 數據插入模版時,沒有使用正確的編碼,表現出模版中的新插入數據爲亂碼
解決方法:在result的配置中,指定charset,s2的FreemarkerResult.java會將charset傳遞freemarker
<action name="ListPersons" class="ListPersons">
<result type="freemarker">
<param name="location">/pages/Person/view.ftl</param>
<param name="contentType"> text/html;charset=UTF-8
</param>
</result>
</action>
(2)提高freemarker的性能
在freemarker.properties中設置:
template_update_delay=60000
避免每次請求都重新載入模版,即充分利用cached的模版
(3)儘量使用freemarker本身的提供的tag,使用S2 tags 的標籤會在性能上有所損失
(4)freemarker的標籤種類:
- ${..}:FreeMarker will replace it in the output with the actual value of the thing in the curly brackets. They are called interpolation s.
- # ,代表是FTL tags(FreeMarker Template Language tags) ,hey are instructions to FreeMarker and will not be printed to the output
- <#if ...></#if>
- <#list totalList as elementObject>...</#list>
- @ ,代表用戶自定義的標籤
- <#-- --> 註釋標籤,注意不是<!-- -->
(5)一些特殊的指令:
- r代表原樣輸出:${r"C:/foo/bar"}
- <#list ["winter", "spring", "summer", "autumn"] as x>${x}</#list>
- ?引出內置指令
- String處理指令:
- html:特殊的html字符將會被轉義,比如"<",處理後的結果是<
- cap_first 、lower_case 、upper_case
- trim :除去字符串前後的空格
- sequences處理指令
- size :返回sequences的大小
- numbers處理指令
- int:number的整數部分,(e.g. -1.9?int is -1)
- String處理指令:
(6)對於null,或者miss value,freemarker會報錯
- ?exists:舊版本的用法
- !:default value operator,語法結構爲: unsafe_expr !default_expr,比如 ${mouse!"No mouse."} 當mouse不存在時,返回default value;
- (product.color)!"red" 這種方式,能夠處理product或者color爲miss value的情況;
- 而product.color!"red"將只處理color爲miss value的情況
- ??: Missing value test operator ,測試是否爲missing value
- unsafe_expr ?? :product.color??將只測試color是否爲null
- (unsafe_expr )??:(product.color)??將測試product和color是否存在null
- <#if mouse??>
- Mouse found
- <#else>
- No mouse found
- </#if>
- Creating mouse...
- <#assign mouse = "Jerry">
- <#if mouse??>
- Mouse found
- <#else>
- No mouse found
- </#if>
(7)模版值插入方式 (interpolation)
- 通用方式 ( Universal interpolations): ${expression }
- 對於字符串:只是簡單輸出
- 對於數值,會自動根據local確定格式,稱爲human audience,否則稱爲computer audience,可以"?c", 比如, <a href="/shop/details?id=${product.id ?c }">Details...</a>,因此這裏的id是給瀏覽器使用的,不需要進行格式化,注意?c只對數值有效
- 對於日期,會使用默認的日期格式轉換,因此需要事先設置好默認的轉換格式,包括date_format , time_format ,atetime_format
- 對於布爾值,不能輸出,會報錯並停止模版的執行,比如${a = 2} 會出錯,但是可以 string built-in來進行轉換
數值處理,具體參考:Built-ins for numbers
http://freemarker.org/docs/ref_builtins_number.html#ref_builtin_string_for_number
數值處理的例子:
<#setting number_format="currency"/>
<#assign answer=42/>
${answer}
${answer?string} <#-- the same as ${answer} -->
${answer?string.number}
${answer?string.currency}
${answer?string.percent}
除了使用內置的formate,可以使用任何用Java decimal number format syntax 書寫的formate,比如
<#setting number_format="0.###E0"/>
<#setting number_format="0"/>
<#setting number_format="#"/>
${1234}
${12345?string("0.####E0")}
更加方便的格式:
<#setting locale="en_US">
US people writes: ${12345678?string(",##0.00")}
<#setting locale="hu">
Hungarian people writes: ${12345678?string(",##0.00")}
日期處理,參考Built-ins for dates
http://freemarker.org/docs/ref_builtins_date.html#ref_builtin_string_for_date
日期處理的例子:
- ${openingTime?string.short}
- ${openingTime?string.medium}
- ${openingTime?string.long}
- ${openingTime?string.full}
- ${nextDiscountDay?string.short}
- ${nextDiscountDay?string.medium}
- ${nextDiscountDay?string.long}
- ${nextDiscountDay?string.full}
- ${lastUpdated?string.short}
- ${lastUpdated?string.medium}
- ${lastUpdated?string.long}
- ${lastUpdated?string.full}
注意:
由於java語言中的Date類型的不足,freemarker不能根據Date變量判斷出變量包含的部分(日期、時間還是全部),在這種情況下,freemarker
不能正確顯示出${lastUpdated?string.short} 或者 simply ${lastUpdated},因此,可以通過?date, ?time and ?datetime built-ins
來幫助freemarker來進行判斷,比如${lastUpdated?datetime?string.short}
除了使用內置的日期轉換格式外,可以自己指定日期的格式,使用的是Java date format syntax,比如:
- ${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")}
- ${lastUpdated?string("EEE, MMM d, ''yy")}
- ${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")}
數值專用方式 ( Numerical interpolations):#{expression } or #{expression ; format },這是數值專用的輸出方式,但是 最好使用通用方式的string built-in或者number_format 來完成轉換,Numerical interpolations方式將會被停用
(8)創建自定義模版
- <#macro greet>
- <font size="+2">Hello Joe!</font>
- </#macro>
C 一些常用方法或注意事項
表達式轉換類
${expression} 計算expression 並輸出
#{ expression } 數字計算#{ expression ;format} 安格式輸出數字format 爲M 和m
M 表示小數點後最多的位數,m 表示小數點後最少的位數如#{121.2322;m2M2} 輸出121.23
數字循環
1..5 表示從1 到5 ,原型number..number
對浮點取整數
${123.23?int} 輸出 123
給變量默認值
${var?default("hello world")?html} 如果var is null 那麼將會被hello world 替代
判斷對象是不是 null
語法
輸出
1. 0.5
2. 1
3. 1.5
4. 2 Last!
包含body 的宏
輸出
Test text, and the params: a, b, 23
Test text, and the params: a, b, -1
Test text, and the params: a, Bar, 23
Test text, and the params: a, Bar, -1
定義循環輸出的宏
用例
語法
輸出
1,2
1.2
因爲匈牙利是採用", "作爲十進制的分隔符,美國是用". "
用來設置整個系統的一個環境
locale
number_format
boolean_format
date_format , time_format , datetime_format
time_zone
classic_compatible
用例
假如當前是匈牙利的設置,然後修改成美國
語法
全局賦值語法,利用這個語法給變量賦值,那麼這個變量在所有的namespace [A1] 中是可見的, 如果這個變量被當前的assign 語法覆蓋 如<#global x=2> <#assign x=1> 在當前頁面裏x=2 將被隱藏,或者通過${.global.x} 來訪問
語法
用例
生成變量,並且給變量賦值
給seasons賦予序列值
語法
相同表達式
用例
主要使用在相似的字符串變量輸出,比如某一個模塊的所有字符串輸出都必須是html安全的,這個時候就可以使用
該表達式
語法
用來壓縮空白空間和空白的行
語法
用例
假設mylib.ftl 裏定義了宏copyright 那麼我們在其他模板頁面裏可以這樣使用
語法
輸出結果:
Some test
Yeah.
Copyright 2001-2002 Juila Smith
All rights reserved.
模板文件
用例
/common/copyright.ftl 包含內容
語法
用例
語法
如果x=1 輸出 1 2, x=2 輸出 2, x=3 輸出d
數字
字符串