OECP社區有不少Freemaker的技巧及用法,貌似沒有對Freemaker作出詳細介紹的文章,因此今天爲你們上傳一篇介紹Freemaker的文章。
Freemaker是一個強大的模板引擎,相比velocity而言,其強大的過程調用、遞歸、閉包回調,功能讓freemaker能夠完成幾乎全部咱們所想的功能。從我的見解而言,freemaker徹底有能力做爲MDA(模型驅動架構)的代碼輔助生成工具。
freemaker首先吸引眼球的是它強大的過程調用和遞歸處理能力,其次則是xml風格的語法結構有着明顯的邊界,不象velocity要注意段落之間要留空格。
在使用以前咱們先要設置運行環境,在使用Freemaker的時候,咱們須要下載相關的程序:
freemaker: http://freemarker.sourceforge.net/
fmpp: http://fmpp.sourceforge.net/
其中fmpp是一個freemaker的輔助工具,有了它,咱們能夠實現更多的功能。如下例子必須fmpp輔助。
這裏咱們首先提出問題。你們看以下的一個xml文件,雖然freemaker的能力不只在於處理xml文件,可是用xml做爲例子更直觀一些:
<? xml version = ' 1.0 ' encoding = " gb2312 " ?>
< types xmlns:xsi = " http://www.w3.org/2001/XMLSchema-instance " xmlns = " urn:DruleForm-Lite.xsd " >
< type name = " Type1 " >
< labels >
< label lang = " zh-CN " value = " 投保單" />
</ labels >
< field name = " Field11 " type = " Float " lbound = " 1 " ubound = " 1 " >
< labels >
< label lang = " zh-CN " value = " 投保單ID " />
</ labels >
</ field >
< field name = " Field12 " type = " String " lbound = " 1 " ubound = " * " />
< field name = " Field13 " type = " Integer " lbound = " 1 " ubound = " * " />
< field name = " Field14 " type = " Type2 " lbound = " 1 " ubound = " * " >
< type name = " Type2 " >
< field name = " Field21 " type = " String " lbound = " 1 " ubound = " * " />
< field name = " Field22 " type = " Integer " lbound = " 1 " ubound = " * " />
</ type >
</ field >
< field name = " Field15 " type = " InsuranceProduct " lbound = " 1 " ubound = " * " />
< type >
< type name = " Type3 " >
< field name = " Field31 " type = " Type1 " lbound = " 1 " ubound = " * " />
</ type >
</ types >
[代碼1]
咱們的任務是把這個文件轉化爲相應的C#代碼。你們先看轉換模板的代碼:
1 < #ftl ns_prefixes = { " ns " : " urn:DruleForm-Lite.xsd " } >
2 < # -- 定義xml namespace,以便在如下代碼中使用,注意,ftl指令必須使用單獨的行 -->
3 < @pp.setOutputEncoding encoding = " gb2312 " /> < # -- 使用fmpp提供的函數來設置輸出編碼 -->
4
5 < #recurse doc > < # -- 根入口,代碼1部分的xml存放在變量doc中,doc變量的填充由fmpp根據config.fmpp中的配置進行 -->
6
7 < #macro " ns:types " > < # -- xslt風格的匹配處理入口 -->
8 < #recurse > < # -- 直接進行types節點內的匹配 -->
9 </ #macro >
10
11 < #macro " ns:type " > < # -- 匹配type節點 -->
12 class $ {.node.@name} < # -- 其中.node是保留字,表示當前節點,引用的@name是xslt風格 -->
13 {
14 < #recurse > < # -- 繼續匹配 -->
15 }
16 </ #macro >
17
18 < #macro " ns:field " >
19 public $ {.node.@type} $ {.node.@name} ;
20 </ #macro >
21
22 < #macro @element > < # -- 全部沒有定義匹配的節點到這裏處理 -->
23 </ #macro >
[代碼2]
咱們使用的配置文件設置以下:
sourceRoot: src
outputRoot: out
logFile: log.fmpp
modes: [
copy(common /** */ /** /*.*, resource/*.*)
execute(*.ftl)
ignore(templates/*.*, .project, * */ * .xml, xml /**/ /* .*, *.js)
]
removeExtensions: ftl
sourceEncoding: gb2312
data: {
doc: xml(freemaker.xml)
}
[代碼3]
而後咱們在dos模式下運行指令:
E:\work\blogs\freemaker > f:\download\freemaker\fmpp\bin\fmpp
最後的輸出結果是這樣的,存放在文件out\freemaker.中:
class Type1 {
public Float Field11;
public String Field12;
public Integer Field13;
public Type2 Field14;
public Float Field15;
}
class Type3 {
public Type1 Field31;
}
[代碼4]
先來解釋一下freemaker的基本語法了,
< # > 中存放全部freemaker的內容,以外的內容所有原樣輸出。
< @ /> 是函數調用
兩個定界符內的內容中,第一個符號表示指令或者函數名,其後的跟隨參數。freemaker提供的控制包括以下:
1 : 條件判斷
< # if condition >
< # else if condition >
< # else >
</ # if >
2 : 遍歷hash表或者collection(freemaker稱做sequence)的成員
< #list hash_or_seq as var >
</ #list >
3 : 宏,無返回參數
< #macro name param1 param2 >
< #nested param >
</ #macro >
4 : 函數,有返回參數
< #function name param1 param2 >
< # return val >
</ #function >
5 : 用函數對var進行轉換,freemaker稱爲build-ins。實際內部實現相似member_function(var, ...)
var ? member_function()
6 : 取子字符串,相似substring(stringA, M, N)
stringA[M .. N]
7 : 直接定義一個hash表
{key:value, key2:value2 }
8 : 直接定義一個序列
[item0, item1, item2 ]
9 : 存取hash表中key對應的元素
hash0[key0]
10 : 存取序列指定下標的元素
seq0[ 5 ]
11 : 調用函數function1
< @function1 param0 param1 />
12 : 調用宏,並處理宏的嵌套
< @macro0 param0 param1 ; nest_param0 nest_param1 >
nest_body
</ @macro >
13 : 定義變量並初始化
< #assign var = value >
14 : 在macro 或者function 中定義局部變量並初始化
< #local var = value >
15 : 定義全局變量並初始化
< #global var = value >
16 : 輸出並替換爲表達式的值
$ {var}
17 : 調用macro匹配xmlnode自己及其子節點
< #visit xmlnode >
18 : 調用macro匹配xmlnode的子節點
< #recurse xmlnode >
你們仔細對比xml文件,發現少了什麼嗎?對了,少了一個Type2定義,咱們把代碼2中的ns:type匹配(第11行)修改一下:
< #macro " ns:field " >
public $ {.node.@type} $ {.node.@name} ;
< #recurse > < # -- 深刻處理子節點 -->
</ #macro >
[代碼5]
結果輸出文件中的內容就變爲以下:
class Type1 {
public Float Field11;
public String Field12;
public Integer Field13;
public Type2 Field14;
class Type2 {
public String Field21;
public Integer Field22;
}
public Float Field15;
}
class Type3 {
public Type1 Field31;
}
[代碼6]
若是各位有意向把Type2提到跟Type1和Type3同一級別的位置,那麼咱們要繼續修改代碼了。把代碼2的<#recurse doc>行(第5行)修改爲以下:
< #assign inner_types = pp.newWritableHash() > < # -- 調用fmpp功能函數,生成一個可寫的hash -->
< #recurse doc > < # -- 根入口,代碼1部分的xml存放在變量doc中,doc變量的填充由fmpp根據config.fmpp中的配置進行 -->
< # if inner_types ? size gt 0 > < # -- 若是存放有類型 -->
< #list inner_types ? values as node > < # -- 遍歷哈西表的值 -->
< #visit node > < # -- 激活相應的macro處理,相似於xslt的apply - template。你們把visit改爲recurse看一下不一樣的效果 -->
</ #list >
</ # if >
[代碼7]
同時把macro ns:field(第18行)修改爲以下:
< #macro " ns:field " >
public $ {.node.@type} $ {.node.@name} ;
< # if .node[ " ns:type " ] ? has_content > < # -- 若是當前節點下存在type節點 -->
< #local t = .node[ " ns:type " ] >
< @pp.set hash = inner_types key = " ${t.@name} " value = t /> < # -- 哈西表中增長內容,key爲嵌套類型的name屬性,value爲該類型節點 -->
</ # if >
</ #macro >
[代碼8]
運行獲得輸出文件相似這樣:
class Type1 {
public Float Field11;
public String Field12;
public Integer Field13;
public Type2 Field14;
public Float Field15;
}
class Type3 {
public Type1 Field31;
}
class Type2 {
public String Field21;
public Integer Field22;
}
[代碼9]
你們比較一下,看看咱們修改的地方出現了哪些效果?而後記得你們要作另外2件事情:
1。把第一行修改爲爲<#ftl ns_prefixes={"D": "urn:DruleForm-Lite.xsd"}> ,而後把全部的<#macro "ns:type"> 修改爲<#macro type>,把全部的.node["ns:type"]修改爲.node.type,看看能不能運行?是否是以爲簡單方便些了?記住,第一行的那個D表示是default namespace的意思哦。
2。在第二行插入<#compress>,在最後一行添加</#compress>。再運行一下看看結果有什麼不一樣?
一個例子下來,你們基本對freemaker有了一些感受了,爲了糾正你們認爲freemaker就是一個xml處理工具的誤解,咱們再來作一個簡單的實驗。此次咱們要作的是一個正常的編程題目,作一個100之內的Fibonacci數列的程序。程序以下:
迭代次數:
< #list 1 .. 10 as n >
$ {n} = $ {fibo(n)}
</ #list >
< #compress >
< #function fibo n >
< # if n lte 1 >
< # return 1 >
< #elseif n = 2 >
< # return 1 >
< # else >
< # return fibo(n - 1 ) + fibo(n - 2 ) >
</ # if >
</ #function >
</ #compress >
[代碼10]
這個例子裏邊有一些問題須要注意,你們看個人#if n lte 1 這一行,爲何我這麼寫?由於常規的大於小於號和xml的節點有衝突,爲了不問題,因此用gt(>) gte(>=) lt(<) lte(<=) 來表明。
另外,複雜的字符串處理如何來作?就留做家庭做業吧,你們記得取substr的方法是str[first .. last] 就能夠了。以下的例子可能會給你一點提示:
< #assign str = " hello!$world! " >
< #assign mid = (str ? length + 1 ) / 2 - 1 >
< #list mid .. 0 as cnt >
$ {str[(mid - cnt) .. (mid + cnt)] ? left_pad(mid * 2 )}
</ #list >
[代碼11]
最後,說一下很是有用的macro的nested指令,沒有它,也許freemaker會失去大部分的魅力。我我的認爲這也是freemaker全面超越velocity的地方。你們先看一下代碼:
< #assign msg = " hello " >
< @macro0 ; index >
$ {msg} $ {index}
</ @macro0 >
< #macro macro0 >
< #list 0 .. 10 as number >
< #nested number >
</ #list >
</ #macro >
[代碼12]
這段代碼的做用就是一個閉包(closure)。咱們用java的匿名類實現相同的功能就是這樣:
interface ICallback
{
public void call( int index);
}
void Main()
{
String msg = " hello " ;
macro0(
new ICallback()
{
public void call( int index)
{
System.out.println(msg + index.toString());
}
}
);
}
void macro0(ICallback callback)
{
for ( int i = 0 ; i < 10 ; ++ i)
{
callback.call(i);
}
}
經過Freemaker簡介,如今瞭解Freemaker了吧,瞭解以後也要分享本身對Freemaker的心得哦。
java