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