<script type="text/javascript"> </script> <script type="text/javascript"> </script> <script type="text/javascript"> </script>
|
转义序列 | 含义 |
---|---|
/" | 双引号(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]}结果是(注意第一个字符的索引是0):
${user[1..4]}
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为5):
${x / 2}
${12 % 10}
-75操作符两边必须是数字,因此下面的代码是错误的:
2.5
2
${3 * "5"} <#-- WRONG! -->使用+操作符时,如果一边是数字,一边是字符串,就会自动将数字转换为字符串,例如:
${3 + "5"}输出结果是:
35使用内建的int(后面讲述)获得整数部分,例如:
${(x/2)?int}输出结果是(假设x为5):
${1.1?int}
${1.999?int}
${-1.1?int}
${-1.999?int}
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插入日期值:根据缺省格式(由#setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string格式化单个Interpolation,下面是一个使用格式模式的例子:
$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插入布尔值:根据缺省格式(由#setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string格式化单个Interpolation,下面是一个例子:
Tue, Apr 8, '03
Tuesday, April 08, 2003, 09:24:44 PM (PDT)
<#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>作为用户定义指令使用宏变量时,使用@替代FTL标记中的#
<font size="+2">Hello Joe!</font>
</#macro>
<@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">这样<@greet person="Fred"/>就正确了
<font size="+2" color="${color}">Hello ${person}!</font>
</#macro>
宏的参数是局部变量,只能在宏定义中有效
- 嵌套内容
用户定义指令可以有嵌套内容,使用<#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.嵌套内容可以是有效的FTL,下面是一个有些复杂的例子: <@border> <ul> <@do_thrice> <li><@greet person="Joe"/> </@do_thrice> </ul> </@border> }}} 输出结果:
Anything.
Anything.
<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 = "jsmith@acme.com">
<#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
可以使用assign指令在导入的名字空间中创建或替代变量,下面是一个例子:
<#import "/lib/my_test.ftl" as my>输出结果:
${my.mail}
<#assign mail="jsmith@other.com" in my>
${my.mail}
jsmith@acme.com数据模型中的变量任何地方都可见,也包括不同的名字空间,下面是修改的库:
jsmith@other.com
<#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>
Fred@acme.com
补充(静态方法的调用):
方法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...
<script type="text/javascript"> </script>
<script type="text/javascript"> </script>