FreeMarker設計指南
FreeMarker設計指南
1、快速入門
(1)模板 + 數據模型 = 輸出
l FreeMarker基于設計者和程序員是具有不同專業技能的不同個體的觀念
l 他們是分工勞動的:設計者專注于表示——創建HTML文件、圖片、Web頁面的其它可視化方面;程序員創建系統,生成設計頁面要顯示的數據
l 經常會遇到的問題是:在Web頁面(或其它類型的文檔)中顯示的信息在設計頁面時是無效的,是基于動態數據的
l 在這里,你可以在HTML(或其它要輸出的文本)中加入一些特定指令,FreeMarker會在輸出頁面給最終用戶時,用適當的數據替代這些代碼
l 下面是一個例子:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
l 這個例子是在簡單的HTML中加入了一些由${…}包圍的特定代碼,這些特定代碼是FreeMarker的指令,而包含FreeMarker的指令的文件就稱為模板(Template)
l 至于user、latestProduct.url和latestProduct.name來自于數據模型(data model)
l 數據模型由程序員編程來創建,向模板提供變化的信息,這些信息來自于數據庫、文件,甚至于在程序中直接生成
l 模板設計者不關心數據從那兒來,只知道使用已經建立的數據模型
l 下面是一個可能的數據模型:
(root)
|
+- user = "Big Joe"
|
+- latestProduct
|
+- url = "products/greenmouse.html"
|
+- name = "green mouse"
l 數據模型類似于計算機的文件系統,latestProduct可以看作是
(root)
|
+- mouse = "Yerri"
|
+- age = 12
|
+- color = "brown">
${mouse} <#-- use mouse as scalar -->
${mouse.age} <#-- use mouse as hash -->
${mouse.color} <#-- use mouse as hash -->
Yerri
12
brown
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)}
3、模板
(1)整體結構
l 模板使用FTL(FreeMarker模板語言)編寫,是下面各部分的一個組合:
? 文本:直接輸出
? Interpolation:由${和},或#{和}來限定,計算值替代輸出
? FTL標記:FreeMarker指令,和HTML標記類似,名字前加#予以區分,不會輸出
? 注釋:由<#--和-->限定,不會輸出
l 下面是以一個具體模板例子:
<html>[BR]
<head>[BR]
<title>Welcome!</title>[BR]
</head>[BR]
<body>[BR]
<#-- Greet the user with his/her name -->[BR]
<h1>Welcome ${user}!</h1>[BR]
<p>We have these animals:[BR]
<ul>[BR]
<#list animals as being>[BR]
<li>${being.name} for ${being.price} Euros[BR]
</#list>[BR]
</ul>[BR]
</body>[BR]
</html>
l [BR]是用于換行的特殊字符序列
l 注意事項:
? FTL區分大小寫,所以list是正確的FTL指令,而List不是;${name}和${NAME}是不同的
? Interpolation只能在文本中使用
? FTL標記不能位于另一個FTL標記內部,例如:
<#if <#include 'foo'>='bar'>...</if>
? 注釋可以位于FTL標記和Interpolation內部,如下面的例子:
<h1>Welcome ${user <#-- The name of user -->}!</h1>[BR]
<p>We have these animals:[BR]
<ul>[BR]
<#list <#-- some comment... --> animals as <#-- again... --> being>[BR]
...
? 多余的空白字符會在模板輸出時移除
(2)指令
l 在FreeMarker中,使用FTL標記引用指令
l 有三種FTL標記,這和HTML標記是類似的:
? 開始標記:<#directivename parameters>
? 結束標記:</#directivename>
? 空內容指令標記:<#directivename parameters/>
l 有兩種類型的指令:預定義指令和用戶定義指令
l 用戶定義指令要使用@替換#,如<@mydirective>...</@mydirective>(會在后面講述)
l FTL標記不能夠交叉,而應該正確的嵌套,如下面的代碼是錯誤的:
<ul>
<#list animals as being>
<li>${being.name} for ${being.price} Euros
<#if use = "Big Joe">
(except for you)
</#list>
</#if> <#-- WRONG! -->
</ul>
l 如果使用不存在的指令,FreeMarker不會使用模板輸出,而是產生一個錯誤消息
l FreeMarker會忽略FTL標記中的空白字符,如下面的例子:
<#list[BR]
animals as[BR]
being[BR]
>[BR]
${being.name} for ${being.price} Euros[BR]
</#list >
l 但是,<、</和指令之間不允許有空白字符
(3)表達式
l 直接指定值
? 字符串
n 使用單引號或雙引號限定
n 如果包含特殊字符需要轉義,如下面的例子:
${"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: \
n 下面是支持的轉義序列:
轉義序列 |
含義 |
\" |
雙引號(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代碼 |
n 有一類特殊的字符串稱為raw字符串,被認為是純文本,其中的\和{等不具有特殊含義,該類字符串在引號前面加r,下面是一個例子:
${r"${foo}"}
${r"C:\foo\bar"}
輸出的結果是:
${foo}
C:\foo\bar
? 數字
n 直接輸入,不需要引號
n 精度數字使用“.”分隔,不能使用分組符號
n 目前版本不支持科學計數法,所以“1E3”是錯誤的
n 不能省略小數點前面的0,所以“.5”是錯誤的
n 數字8、+8、08和8.00都是相同的
? 布爾值
n true和false,不使用引號
? 序列
n 由逗號分隔的子變量列表,由方括號限定,下面是一個例子:
<#list ["winter", "spring", "summer", "autumn"] as x>
${x}
</#list>
輸出的結果是:
winter
spring
summer
autumn
n 列表的項目是表達式,所以可以有下面的例子:
[2 + 2, [1, 2, 3, 4], "whatnot"]
n 可以使用數字范圍定義數字序列,例如2..5等同于[2, 3, 4, 5],但是更有效率,注意數字范圍沒有方括號
n 可以定義反遞增的數字范圍,如5..2
? 散列(hash)
n 由逗號分隔的鍵/值列表,由大括號限定,鍵和值之間用冒號分隔,下面是一個例子:
{"name":"green mouse", "price":150}
n 鍵和值都是表達式,但是鍵必須是字符串
l 獲取變量
? 頂層變量: ${variable},變量名只能是字母、數字、下劃線、$、@和#的組合,且不能以數字開頭
? 從散列中獲取數據
n 可以使用點語法或方括號語法,假設有下面的數據模型:
(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"]
n 使用點語法,變量名字有頂層變量一樣的限制,但方括號語法沒有該限制,因為名字是任意表達式的結果
? 從序列獲得數據:和散列的方括號語法語法一樣,只是方括號中的表達式值必須是數字;注意:第一個項目的索引是0
? 序列片斷:使用[startIndex..endIndex]語法,從序列中獲得序列片斷(也是序列);startIndex和endIndex是結果為數字的表達式
? 特殊變量:FreeMarker內定義變量,使用.variablename語法訪問
${"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[0]}${user[4]}
${user[1..4]}
BJ
ig J
<#list ["Joe", "Fred"] + ["Julia", "Kate"] as user>
- ${user}
</#list>
- Joe
- Fred
- Julia
- Kate
<#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}
-75
2.5
2
${3 * "5"} <#-- WRONG! -->
${3 + "5"}
35
${(x/2)?int}
${1.1?int}
${1.999?int}
${-1.1?int}
${-1.999?int}
2
1
1
-1
-1
<#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>
${test?html}
${test?upper_case?html}
Tom & Jerry
TOM & JERRY
操作符組 |
操作符 |
后綴 |
[subvarName] [subStringRange] . (methodParams) |
一元 |
+expr、-expr、! |
內建 |
? |
乘法 |
*、 / 、% |
加法 |
+、- |
關系 |
<、>、<=、>=(lt、lte、gt、gte) |
相等 |
==(=)、!= |
邏輯and |
&& |
邏輯or |
|| |
數字范圍 |
.. |
<#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%
${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)
<#assign foo=true/>
${foo?string("yes", "no")}
yes
<#-- 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 -->
<#macro greet>
<font size="+2">Hello Joe!</font>
</#macro>
<@greet></@greet>
<@greet/>
<#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>
<@greet person=Fred/>
<#macro greet person color>
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
<@greet person="Fred" color="black"/>
<@greet color="black" person="Fred"/>
<@greet person="Fred" color="black" background="green"/>
<@greet person="Fred"/>
<#macro greet person color="black">
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
<#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>
<#macro do_thrice>
<#nested>
<#nested>
<#nested>
</#macro>
<@do_thrice>
Anything.
</@do_thrice>
Anything.
Anything.
Anything.
<@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: ? ? ?
<#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)在模板中定義變量
l 在模板中定義的變量有三種類型:
? plain變量:可以在模板的任何地方訪問,包括使用include指令插入的模板,使用assign指令創建和替換
? 局部變量:在宏定義體中有效,使用local指令創建和替換
? 循環變量:只能存在于指令的嵌套內容,由指令(如list)自動創建;宏的參數是局部變量,而不是循環變量
l 局部變量隱藏(而不是覆蓋)同名的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
l 內部循環變量隱藏同名的外部循環變量,如:
<#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
loop 2
loop 3
loop 2
loop 1
l 模板中的變量會隱藏(而不是覆蓋)數據模型中同名變量,如果需要訪問數據模型中的同名變量,使用特殊變量global,下面的例子假設數據模型中的user的值是Big Joe:
<#assign user = "Joe Hider">
${user} <#-- prints: Joe Hider -->
${.globals.user} <#-- prints: Big Joe -->
(3)名字空間
l 通常情況,只使用一個名字空間,稱為主名字空間
l 為了創建可重用的宏、變換器或其它變量的集合(通常稱庫),必須使用多名字空間,其目的是防止同名沖突
l 創建庫
? 下面是一個創建庫的例子(假設保存在lib/my_test.ftl中):
<#macro copyright date>
<p>Copyright (C) ${date} Julia Smith. All rights reserved.
<br>Email: ${mail}</p>
</#macro>
<#assign mail = "jsmith@acme.com">
? 使用import指令導入庫到模板中,Freemarker會為導入的庫創建新的名字空間,并可以通過import指令中指定的散列變量訪問庫中的變量:
<#import "/lib/my_test.ftl" as my>
<#assign mail="fred@acme.com">
<@my.copyright date="1999-2002"/>
${my.mail}
${mail}
輸出結果:
<p>Copyright (C) 1999-2002 Julia Smith. All rights reserved.
<br>Email: jsmith@acme.com</p>
jsmith@acme.com
fred@acme.com
可以看到例子中使用的兩個同名變量并沒有沖突,因為它們位于不同的名字空間
l 可以使用assign指令在導入的名字空間中創建或替代變量,下面是一個例子:
<#import "/lib/my_test.ftl" as my>
${my.mail}
<#assign mail="jsmith@other.com" in my>
${my.mail}
l 輸出結果:
jsmith@acme.com
jsmith@other.com
l 數據模型中的變量任何地方都可見,也包括不同的名字空間,下面是修改的庫:
<#macro copyright date>
<p>Copyright (C) ${date} ${user}. All rights reserved.</p>
</#macro>
<#assign mail = "${user}@acme.com">
l 假設數據模型中的user變量的值是Fred,則下面的代碼:
<#import "/lib/my_test.ftl" as my>
<@my.copyright date="1999-2002"/>
${my.mail}
l 輸出結果:
<p>Copyright (C) 1999-2002 Fred. All rights reserved.</p>
Fred@acme.com
posted on 2006-03-07 20:56 靜夜思 閱讀(249) 評論(0) 編輯 收藏 所屬分類: 開源軟件