快速入門
(1)模板 + 數據模型 = 輸出
FreeMarker基於設計者和程序員是具有不同專業技能的不同個體的觀念他們是分工勞動的:
設計者專注於表示——創建HTML文件、圖片、Web頁面的其它可視化方面;
程序員創建系統,生成設計頁面要顯示的數據。
經常會遇到的問題是:在Web頁面(或其它類型的文檔)中顯示的信息在設計頁面時是無效的,是基於動態數據的。在這裏,你可以在HTML(或其它要輸出的文本)中加入一些特定指令,FreeMarker會在輸出頁面給最終用戶時,用適當的數據替代這些代碼。
先來解釋一下freemaker的基本語法了,
<# ... > 中存放所有freemaker的內容,之外的內容全部原樣輸出。
<@ ... /> 是函數調用
兩個定界符內的內容中,第一個符號表示指令或者函數名,其後的跟隨參數。freemaker提供的控制包括如下:
<#if condition><#elseif condition><#else> 條件判斷
<#list hash_or_seq as var> 遍歷hash表或者collection(freemaker稱作sequence)的成員
<#macro name param1 param2 ... ><#nested param> 宏,無返回參數
<#function name param1 param2><#return val>函數,有返回參數
var?member_function(...) 用函數對var進行轉換,freemaker稱爲build-ins。實際內部實現類似member_function(var, ...)
stringA[M .. N] 取子字符串,類似substring(stringA, M, N)
{key:value, key2:value2 ...} 直接定義一個hash表
[item0, item1, item2 ...] 直接定義一個序列
hash0[key0] 存取hash表中key對應的元素
seq0[5] 存取序列指定下標的元素
<@function1 param0 param1 ... /> 調用函數function1
<@macro0 param0 param1 ; nest_param0 nest_param1 ...> nest_body </@macro> 調用宏,並處理宏的嵌套
<#assign var = value > 定義變量並初始化
<#local var = value> 在 macro 或者 function 中定義局部變量並初始化
<#global var = value > 定義全局變量並初始化
${var} 輸出並替換爲表達式的值
<#visit xmlnode> 調用macro匹配xmlnode本身及其子節點
<#recurse xmlnode> 調用macro匹配xmlnode的子節點
下面是一個例子:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
這個例子是在簡單的HTML中加入了一些由${…}包圍的特定代碼,這些特定代碼是FreeMarker的指令,而包含FreeMarker的指令的文件就稱爲模板(Template)。
至於user、latestProduct.url和latestProduct.name來自於數據模型(data model)。
數據模型由程序員編程來創建,向模板提供變化的信息,這些信息來自於數據庫、文件,甚至於在程序中直接生成。
模板設計者不關心數據從那兒來,只知道使用已經建立的數據模型。
下面是一個可能的數據模型:
(root)
|
+- user = "Big Joe"
|
+- latestProduct
|
+- url = "products/greenmouse.html"
|
+- name = "green mouse"
數據模型類似於計算機的文件系統,latestProduct可以看作是目錄。
2、數據模型
(1)基礎
在快速入門中介紹了在模板中使用的三種基本對象類型:scalars、hashes 和sequences,其實還可以有其它更多的能力:
- scalars:存儲單值
- hashes:充當其它對象的容器,每個都關聯一個唯一的查詢名字
- sequences:充當其它對象的容器,按次序訪問
- 方法:通過傳遞的參數進行計算,以新對象返回結果
- 用戶自定義FTL標記:宏和變換器
通常每個變量只具有上述的一種能力,但一個變量可以具有多個上述能力,如下面的例子:
(root)
|
+- mouse = "Yerri"
|
+- age = 12
|
+- color = "brown">
mouse既是scalars又是hashes,將上面的數據模型合併到下面的模板:
${mouse} <#-- use mouse as scalar -->
${mouse.age} <#-- use mouse as hash -->
${mouse.color} <#-- use mouse as hash -->
輸出結果是:
Yerri
12
brown
(2)Scalar變量
Scalar變量存儲單值,可以是:
- 字符串:簡單文本,在模板中使用引號(單引號或雙引號)括起
- 數字:在模板中直接使用數字值
- 日期:存儲日期/時間相關的數據,可以是日期、時間或日期-時間(Timestamp);通常情況,日期值由程序員加到數據模型中,設計者只需要顯示它們
- 布爾值:true或false,通常在<#if …>標記中使用
(3)hashes 、sequences和集合
有些變量不包含任何可顯示的內容,而是作爲容器包含其它變量,者有兩種類型:
- hashes:具有一個唯一的查詢名字和它包含的每個變量相關聯
- sequences:使用數字和它包含的每個變量相關聯,索引值從0開始
集合變量通常類似sequences,除非無法訪問它的大小和不能使用索引來獲得它的子變量;集合可以看作只能由<#list …>指令使用的受限sequences
(4)方法
方法變量通常是基於給出的參數計算值。
下面的例子假設程序員已經將方法變量avg放到數據模型中,用來計算數字平均值:
The average of 3 and 5 is: ${avg(3, 5)}
The average of 6 and 10 and 20 is: ${avg(6, 10, 20)}
The average of the price of python and elephant is:
${avg(animals.python.price, animals.elephant.price)}
(5)宏和變換器
宏和變換器變量是用戶自定義指令(自定義FTL標記),會在後面講述這些高級特性
(6)節點
節點變量表示爲樹型結構中的一個節點,通常在XML處理中使用,會在後面的專門章節中講
3、模板
(1)整體結構
模板使用FTL(FreeMarker模板語言)編寫,是下面各部分的一個組合:
- 文本:直接輸出
- Interpolation:由${和},或#{和}來限定,計算值替代輸出
- FTL標記:FreeMarker指令,和HTML標記類似,名字前加#予以區分,不會輸出
- 註釋:由<#--和-->限定,不會輸出
下面是以一個具體模板例子:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<#-- Greet the user with his/her name -->
<h1>Welcome ${user}!</h1>
<p>We have these animals:
<ul>
<#list animals as being>
<li>${being.name} for ${being.price} Euros
</#list>
</ul>
</body>
</html>
注意事項:
- FTL區分大小寫,所以list是正確的FTL指令,而List不是;${name}和${NAME}是不同的
- Interpolation只能在文本中使用
- FTL標記不能位於另一個FTL標記內部,例如:
<#if <#include 'foo'>='bar'>...</if>
- 註釋可以位於FTL標記和Interpolation內部,如下面的例子:
<h1>Welcome ${user <#-- The name of user -->}!</h1>
<p>We have these animals:
<ul>
<#list <#-- some comment... --> animals as <#-- again... --> being>
...
- 餘的空白字符會在模板輸出時移除
(2)指令
在FreeMarker中,使用FTL標記引用指令。有三種FTL標記,這和HTML標記是類似的:
- 開始標記:<#directivename parameters>
- 結束標記:</#directivename>
- 空內容指令標記:<#directivename parameters/>
有兩種類型的指令:預定義指令和用戶定義指令。
用戶定義指令要使用@替換#,如<@mydirective>...</@mydirective>(會在後面講述)。
FTL標記不能夠交叉,而應該正確的嵌套,如下面的代碼是錯誤的:
<ul>
<#list animals as being>
<li>${being.name} for ${being.price} Euros
<#if use = "Big Joe">
(except for you)
</#list>
</#if> <#-- WRONG! -->
</ul>
如果使用不存在的指令,FreeMarker不會使用模板輸出,而是產生一個錯誤消息。
FreeMarker會忽略FTL標記中的空白字符,如下面的例子:
<#list
animals as
being
>
${being.name} for ${being.price} Euros
</#list >
但是,<、</和指令之間不允許有空白字符。
(3)表達式
直接指定值
- 字符串
使用單引號或雙引號限定
如果包含特殊字符需要轉義,如下面的例子:
${"It's /"quoted/" and
this is a backslash: //"}
${'It/'s "quoted" and
this is a backslash: //'}
輸出結果是:
It's "quoted" and
this is a backslash: /
It's "quoted" and
this is a backslash: /
下面是支持的轉義序列:
轉義序列 | 含義 |
---|---|
/" | 雙引號(u0022) |
/' | 單引號(u0027) |
反斜槓(u005C) | |
/n | 換行(u000A) |
/r | Return (u000D) |
/t | Tab (u0009) |
/b | Backspace (u0008) |
/f | Form feed (u000C) |
/l | < |
/g | > |
/a | & |
/{ | { |
/xCode | 4位16進制Unicode代碼 |
有一類特殊的字符串稱爲raw字符串,被認爲是純文本,其中的/和{等不具有特殊含義,該類字符串在引號前面加r,下面是一個例子:
${r"${foo}"}
${r"C:/foo/bar"}
輸出的結果是:
${foo}
C:/foo/bar
- 數字
直接輸入,不需要引號
精度數字使用“.”分隔,不能使用分組符號
目前版本不支持科學計數法,所以“1E3”是錯誤的
不能省略小數點前面的0,所以“.5”是錯誤的
數字8、+8、08和8.00都是相同的
- 布爾值
true和false,不使用引號
- 序列
由逗號分隔的子變量列表,由方括號限定,下面是一個例子:
<#list ["winter", "spring", "summer", "autumn"] as x>
${x}
</#list>
輸出的結果是:
winter
spring
summer
autumn
列表的項目是表達式,所以可以有下面的例子:
[2 + 2, [1, 2, 3, 4], "whatnot"]
可以使用數字範圍定義數字序列,例如2..5等同於[2, 3, 4, 5],但是更有效率,注意數字範圍沒有方括號
可以定義反遞增的數字範圍,如5..2
- 散列(hash)
由逗號分隔的鍵/值列表,由大括號限定,鍵和值之間用冒號分隔,下面是一個例子:
{"name":"green mouse", "price":150}
鍵和值都是表達式,但是鍵必須是字符串
獲取變量
- 頂層變量: ${variable},變量名只能是字母、數字、下劃線、$、@和#的組合,且不能以數字開頭
- 從散列中獲取數據
可以使用點語法或方括號語法,假設有下面的數據模型:
(root)
|
+- book
| |
| +- title = "Breeding green mouses"
| |
| +- author
| |
| +- name = "Julia Smith"
| |
| +- info = "Biologist, 1923-1985, Canada"
|
+- test = "title"
下面都是等價的:
book.author.name
book["author"].name
book.author.["name"]
book["author"]["name"]
使用點語法,變量名字有頂層變量一樣的限制,但方括號語法沒有該限制,因爲名字是任意表達式的結果
- 從序列獲得數據:和散列的方括號語法語法一樣,只是方括號中的表達式值必須是數字;注意:第一個項目的索引是0
序列片斷:使用[startIndex..endIndex]語法,從序列中獲得序列片斷(也是序列);startIndex和endIndex是結果爲數字的表達式
- 特殊變量:FreeMarker內定義變量,使用.variablename語法訪問
字符串操作
- Interpolation(或連接操作)
可以使用${..}(或#{..})在文本部分插入表達式的值,例如:
${"Hello ${user}!"}
${"${user}${user}${user}${user}"}
可以使用+操作符獲得同樣的結果
${"Hello " + user + "!"}
${user + user + user + user}
${..}只能用於文本部分,下面的代碼是錯誤的:
<#if ${isBig}>Wow!</#if>
<#if "${isBig}">Wow!</#if>
應該寫成:
<#if isBig>Wow!</#if>
- 子串
例子(假設user的值爲“Big Joe”):
${user[0]}${user[4]}
${user[1..4]}
結果是(注意第一個字符的索引是0):
BJ
ig J
序列操作
- 連接操作:和字符串一樣,使用+,下面是一個例子:
<#list ["Joe", "Fred"] + ["Julia", "Kate"] as user>
- ${user}
</#list>
輸出結果是:
- Joe
- Fred
- Julia
- Kate
散列操作
- 連接操作:和字符串一樣,使用+,如果具有相同的key,右邊的值替代左邊的值,例如:
<#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}>
- Joe is ${ages.Joe}
- Fred is ${ages.Fred}
- Julia is ${ages.Julia}
輸出結果是:
- Joe is 30
- Fred is 25
- Julia is 18
算術運算
- +、-、×、/、%,下面是一個例子:
${x * x - 100}
${x / 2}
${12 % 10}
輸出結果是(假設x爲5):
-75
2.5
2
操作符兩邊必須是數字,因此下面的代碼是錯誤的:
${3 * "5"} <#-- WRONG! -->
使用+操作符時,如果一邊是數字,一邊是字符串,就會自動將數字轉換爲字符串,例如:
${3 + "5"}
輸出結果是:
35
使用內建的int(後面講述)獲得整數部分,例如:
${(x/2)?int}
${1.1?int}
${1.999?int}
${-1.1?int}
${-1.999?int}
輸出結果是(假設x爲5):
2
1
1
-1
-1
- 比較操作符
使用=(或==,完全相等)測試兩個值是否相等,使用!= 測試兩個值是否不相等
=和!=兩邊必須是相同類型的值,否則會產生錯誤,例如<#if 1 = "1">會引起錯誤
Freemarker是精確比較,所以對"x"、"x "和"X"是不相等的
對數字和日期可以使用<、<=、>和>=,但不能用於字符串
由於Freemarker會將>解釋成FTL標記的結束字符,所以對於>和>=可以使用括號來避免這種情況,例如<#if (x > y)>
另一種替代的方法是,使用lt、lte、gt和gte來替代<、<=、>和>=
- 邏輯操作符
&&(and)、||(or)、!(not),只能用於布爾值,否則會產生錯誤
例子:
<#if x < 12 && color = "green">
We have less than 12 things, and they are green.
</#if>
<#if !hot> <#-- here hot must be a boolean -->
It's not hot.
</#if>
- 內建函數
內建函數的用法類似訪問散列的子變量,只是使用“?”替代“.”,下面列出常用的一些函數
-
- 字符串使用的:
html:對字符串進行HTML編碼
cap_first:使字符串第一個字母大寫
lower_case:將字符串轉換成小寫
upper_case:將字符串轉換成大寫
trim:去掉字符串前後的空白字符
-
- 序列使用的:
size:獲得序列中元素的數目
-
- 數字使用的:
int:取得數字的整數部分(如-1.9?int的結果是-1)
例子(假設test保存字符串"Tom & Jerry"):
${test?html}
${test?upper_case?html}
輸出結果是:
Tom & Jerry
TOM & JERRY
- 操作符優先順序
操作符組 | 操作符 |
---|---|
後綴 | [subvarName] [subStringRange] . (methodParams) |
一元 | +expr、-expr、! |
內建 | ? |
乘法 | *、 / 、% |
加法 | +、- |
關係 | <、>、<=、>=(lt、lte、gt、gte) |
相等 | ==(=)、!= |
邏輯and | && |
邏輯or | 雙豎線 |
數字範圍 | .. |
(4)Interpolation
Interpolation有兩種類型:
- 通用Interpolation:${expr}
- 數字Interpolation:#{expr}或#{expr; format}
注意:Interpolation只能用於文本部分
- 通用Interpolation
插入字符串值:直接輸出表達式結果
插入數字值:根據缺省格式(由#setting指令設置)將表達式結果轉換成文本輸出;可以使用內建函數string格式化單個Interpolation,下面是一個例子:
<#setting number_format="currency"/>
<#assign answer=42/>
${answer}
${answer?string} <#-- the same as ${answer} -->
${answer?string.number}
${answer?string.currency}
${answer?string.percent}
輸出結果是:
$42.00
$42.00
42
$42.00
4,200%
插入日期值:根據缺省格式(由#setting指令設置)將表達式結果轉換成文本輸出;可以使用內建函數string格式化單個Interpolation,下面是一個使用格式模式的例子:
${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')'")}
輸出的結果類似下面的格式:
2003-04-08 21:24:44 Pacific Daylight Time
Tue, Apr 8, '03
Tuesday, April 08, 2003, 09:24:44 PM (PDT)
插入布爾值:根據缺省格式(由#setting指令設置)將表達式結果轉換成文本輸出;可以使用內建函數string格式化單個Interpolation,下面是一個例子:
<#assign foo=true/>
${foo?string("yes", "no")}
輸出結果是:
yes
- 數字Interpolation的#{expr; format}形式可以用來格式化數字,format可以是:
mX:小數部分最小X位
MX:小數部分最大X位
例子:
<#-- If the language is US English the output is: -->
<#assign x=2.582/>
<#assign y=4/>
#{x; M2} <#-- 2.58 -->
#{y; M2} <#-- 4 -->
#{x; m1} <#-- 2.6 -->
#{y; m1} <#-- 4.0 -->
#{x; m1M2} <#-- 2.58 -->
#{y; m1M2} <#-- 4.0 -->
4、雜項
(1)用戶定義指令
宏和變換器變量是兩種不同類型的用戶定義指令,它們之間的區別是宏是在模板中使用macro指令定義,而變換器是在模板外由程序定義,這裏只介紹宏
- 基本用法
宏是和某個變量關聯的模板片斷,以便在模板中通過用戶定義指令使用該變量,下面是一個例子:
<#macro greet>
<font size="+2">Hello Joe!</font>
</#macro>
作爲用戶定義指令使用宏變量時,使用@替代FTL標記中的#
<@greet></@greet>
如果沒有體內容,也可以使用:
<@greet/>
- 參數
在macro指令中可以在宏變量之後定義參數,如:
<#macro greet person>
<font size="+2">Hello ${person}!</font>
</#macro>
可以這樣使用這個宏變量:
<@greet person="Fred"/> and <@greet person="Batman"/>
輸出結果是:
<font size="+2">Hello Fred!</font>
and <font size="+2">Hello Batman!</font>
宏的參數是FTL表達式,所以下面的代碼具有不同的意思:
<@greet person=Fred/>
這意味着將Fred變量的值傳給person參數,該值不僅是字符串,還可以是其它類型,甚至是複雜的表達式
可以有多參數,下面是一個例子:
<#macro greet person color>
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
可以這樣使用該宏變量:
<@greet person="Fred" color="black"/>
其中參數的次序是無關的,因此下面是等價的:
<@greet color="black" person="Fred"/>
只能使用在macro指令中定義的參數,並且對所有參數賦值,所以下面的代碼是錯誤的:
<@greet person="Fred" color="black" background="green"/>
<@greet person="Fred"/>
可以在定義參數時指定缺省值,如:
<#macro greet person color="black">
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
這樣<@greet person="Fred"/>就正確了
宏的參數是局部變量,只能在宏定義中有效
- 嵌套內容
用戶定義指令可以有嵌套內容,使用<#nested>指令執行指令開始和結束標記之間的模板片斷
例子:
<#macro border>
<table border=4 cellspacing=0 cellpadding=4><tr><td>
<#nested>
</tr></td></table>
</#macro>
這樣使用該宏變量:
<@border>The bordered text</@border>
輸出結果:
<table border=4 cellspacing=0 cellpadding=4><tr><td>
The bordered text
</tr></td></table>
<#nested>指令可以被多次調用,例如:
<#macro do_thrice>
<#nested>
<#nested>
<#nested>
</#macro>
<@do_thrice>
Anything.
</@do_thrice>
輸出結果:
Anything.
Anything.
Anything.
嵌套內容可以是有效的FTL,下面是一個有些複雜的例子: <@border> <ul> <@do_thrice> <li><@greet person="Joe"/> </@do_thrice> </ul> </@border> }}} 輸出結果:
<table border=4 cellspacing=0 cellpadding=4><tr><td>宏定義中的局部變量對嵌套內容是不可見的,例如:
<ul>
<li><font size="+2">Hello Joe!</font>
<li><font size="+2">Hello Joe!</font>
<li><font size="+2">Hello Joe!</font>
</ul>
</tr></td></table>
<#macro repeat count>輸出結果:
<#local y = "test">
<#list 1..count as x>
${y} ${count}/${x}: <#nested>
</#list>
</#macro>
<@repeat count=3>${y?default("?")} ${x?default("?")} ${count?default("?")}</@repeat>
test 3/1: ? ? ?在宏定義中使用循環變量
test 3/2: ? ? ?
test 3/3: ? ? ?
用戶定義指令可以有循環變量,通常用於重複嵌套內容,基本用法是:作爲nested指令的參數傳遞循環變量的實際值,而在調用用戶定義指令時,在<@…>開始標記的參數後面指定循環變量的名字
例子:
<#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>
1. 0.5
2. 1
3. 1.5
4. 2 Last!
指定的循環變量的數目和用戶定義指令開始標記指定的不同不會有問題
調用時少指定循環變量,則多指定的值不可見
調用時多指定循環變量,多餘的循環變量不會被創建
(2)在模板中定義變量
在模板中定義的變量有三種類型:
- plain變量:可以在模板的任何地方訪問,包括使用include指令插入的模板,使用assign指令創建和替換
- 局部變量:在宏定義體中有效,使用local指令創建和替換
- 循環變量:只能存在於指令的嵌套內容,由指令(如list)自動創建
宏的參數是局部變量,而不是循環變量;局部變量隱藏(而不是覆蓋)同名的plain變量;循環變量隱藏同名的局部變量和plain變量,下面是一個例子:
<#assign x = "plain">輸出結果:
1. ${x} <#-- we see the plain var. here -->
<@test/>
6. ${x} <#-- the value of plain var. was not changed -->
<#list ["loop"] as x>
7. ${x} <#-- now the loop var. hides the plain var. -->
<#assign x = "plain2"> <#-- replace the plain var, hiding does not mater here -->
8. ${x} <#-- it still hides the plain var. -->
</#list>
9. ${x} <#-- the new value of plain var. -->
<#macro test>
2. ${x} <#-- we still see the plain var. here -->
<#local x = "local">
3. ${x} <#-- now the local var. hides it -->
<#list ["loop"] as x>
4. ${x} <#-- now the loop var. hides the local var. -->
</#list>
5. ${x} <#-- now we see the local var. again -->
</#macro>
1. plain
2. plain
3. local
4. loop
5. local
6. plain
7. loop
8. loop
9. plain2
內部循環變量隱藏同名的外部循環變量,如:
<#list ["loop 1"] as x>輸出結果:
${x}
<#list ["loop 2"] as x>
${x}
<#list ["loop 3"] as x>
${x}
</#list>
${x}
</#list>
${x}
</#list>
loop 1模板中的變量會隱藏(而不是覆蓋)數據模型中同名變量,如果需要訪問數據模型中的同名變量,使用特殊變量global,下面的例子假設數據模型中的user的值是Big Joe:
loop 2
loop 3
loop 2
loop 1
<#assign user = "Joe Hider">
${user} <#-- prints: Joe Hider -->
${.globals.user} <#-- prints: Big Joe -->
(3)名字空間
通常情況,只使用一個名字空間,稱爲主名字空間
爲了創建可重用的宏、變換器或其它變量的集合(通常稱庫),必須使用多名字空間,其目的是防止同名衝突
- 創建庫
下面是一個創建庫的例子(假設保存在lib/my_test.ftl中):
<#macro copyright date>使用import指令導入庫到模板中,Freemarker會爲導入的庫創建新的名字空間,並可以通過import指令中指定的散列變量訪問庫中的變量:
<p>Copyright (C) ${date} Julia Smith. All rights reserved.
<br>Email: ${mail}</p>
</#macro>
<#assign mail = "[email protected]">
<#import "/lib/my_test.ftl" as my>輸出結果:
<#assign mail="[email protected]">
<@my.copyright date="1999-2002"/>
${my.mail}
${mail}
<p>Copyright (C) 1999-2002 Julia Smith. All rights reserved.可以看到例子中使用的兩個同名變量並沒有衝突,因爲它們位於不同的名字空間
<br>Email: [email protected]</p>
[email protected]
[email protected]
可以使用assign指令在導入的名字空間中創建或替代變量,下面是一個例子:
<#import "/lib/my_test.ftl" as my>輸出結果:
${my.mail}
<#assign mail="[email protected]" in my>
${my.mail}
[email protected]數據模型中的變量任何地方都可見,也包括不同的名字空間,下面是修改的庫:
[email protected]
<#macro copyright date>假設數據模型中的user變量的值是Fred,則下面的代碼:
<p>Copyright (C) ${date} ${user}. All rights reserved.</p>
</#macro>
<#assign mail = "${user}@acme.com">
<#import "/lib/my_test.ftl" as my>輸出結果:
<@my.copyright date="1999-2002"/>
${my.mail}
<p>Copyright (C) 1999-2002 Fred. All rights reserved.</p>
[email protected]
補充(靜態方法的調用):
方法1:
##定義配置文件 freemarkerstatic.properties
_Validator=com.longyou.util.Validator
_Functions=com.longyou.util.Functions
_EscapeUtils=com.longyou.util.EscapeUtils
/調用代碼
${_Functions.toUpperCase("Hello")}<br>
${_EscapeUtils.escape("狼的原野")}
方法2:
${stack.findValue("@package.ClassName@method")}
補充:常用語法
EG.一個對象BOOK
1.輸出 ${book.name}
空值判斷:${book.name?if_exists },
${book.name?default(‘xxx’)}//默認值xxx
${ book.name!"xxx"}//默認值xxx
日期格式:${book.date?string('yyyy-MM-dd')}
數字格式:${book?string.number}--20
${book?string.currency}--<#-- $20.00 -->
${book?string.percent}—<#-- 20% -->
插入布爾值:
<#assign foo=ture />
${foo?string("yes","no")} <#-- yes -->
2.邏輯判斷
a:
<#if condition>...
<#elseif condition2>...
<#elseif condition3>......
<#else>...
其中空值判斷可以寫成<#if book.name?? >
b:
<#switch value>
<#case refValue1>
...
<#break>
<#case refValue2>
...
<#break>
...
<#case refValueN>
...
<#break>
<#default>
...
3.循環讀取
<#list sequence as item>
...
空值判斷<#if bookList?size = 0>
e.g.
<#list employees as e>
${e_index}. ${e.name}
輸出:
1. Readonly
2. Robbin
freemarker中Map的使用
<#list testMap?keys as testKey>
< option value="${testKey}" >
</#list>
freemarker的Eclipse插件
- If you use Eclipse 2.x:
- Open the Window menu, then Open Perspective -> Install/Update
- Click with the right mouse button on the Feature Updates view, then select New -> Site Bookmark
- In the displayed dialog box, type "FreeMarker" for Name and "http://www.freemarker.org/eclipse/update" for URL. Leave the "Bookmark type" radio buttons on "Eclipse update site".
- Click Finish
- Open the tree node under the newly created update site named "FreeMarker", select the "FreeMarker X.Y.Z" feature, and install it using the Install now button in the preview pane.
- If you use Eclipse 3.x:
- Help -> Software updates -> Find and install....
- Choose "Search for new features to install".
- Click Add Update Site..., and type "FreeMarker" for Name and "http://www.freemarker.org/eclipse/update" for URL.
- Check the box of the "FreeMarker" feature.
- "Next"-s until it is installed...