Velocity是一个基于java的模板引擎(template engine)。它允许任何人仅仅简单的使用模板语言(template language)来引用由java代码定义的对象。
当Velocity应用于web开发时,界面设计人员可以和java程序开发人员同步开发一个遵循MVC架构的web站点,也就是说,页面设计人员可以只关注页面的显示效果,而由java程序开发人员关注业务逻辑编码。Velocity将java代码从web页面中分离出来,这样为web站点的长期维护提供了便利,同时也为我们在JSP和PHP之外又提供了一种可选的方案。
Velocity的能力远不止web站点开发这个领域,例如,它可以从模板(template)产生SQL和PostScript、XML,它也可以被当作一个独立工具来产生源代码和报告,或者作为其他系统的集成组件使用。Velocity也可以为Turbine web开发架构提供模板服务(template service)。Velocity+Turbine提供一个模板服务的方式允许一个web应用以一个真正的MVC模型进行开发。Velocity能为我们做什么?
假设你是一家专门出售Mud的在线商店的页面设计人员,让我们暂且称它为“在线MUD商店”。你们的业务很旺,客户下了各种类型和数量的mud订单。他们都是通过输入用户名和密码后才登陆到你的网站,登陆后就允许他们查看订单并购买更多的mud。现在,一种非常流行的mud正在打折销售。另外有一些客户规律性的购买另外一种也在打折但是不是很流行的Bright Red Mud,由于购买的人并不多所以它被安置在页面的边缘。所有用户的信息都是被跟踪并存放于数据库中的,所以某天有一个问题可能会冒出来:为什么不使用velocity来使用户更好的浏览他们感兴趣的商品呢?
Velocity使得web页面的个性化工作非常容易。作为一个web site的设计人员,你希望每个用户登陆时都拥有自己的页面。 你会见了一些公司内的软件工程师,你发现他们每个人都同意客户应该拥有具有个性化的信息。那让我们把软件工程师应该作的事情发在一边,看一看你应该作些什么吧。
你可能在页面内嵌套如下的VTL声明:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<
html
>
<
body
>
Hello $customer.Name!
<
table
>
#foreach( $mud in $nudsOnSpecial )
#if ( $customer.hasPurchased( $mud ) )
<
tr
>
<
td
>$flogger.getPromo( $mud )</
td
>
</
tr
>
#end
#end
</
table
>
</
body
>
</
html
>
|
Velocity Template Language(VTL)介绍
VTL意味着提供最简单、最容易并且最整洁的方式合并页面动态内容。
VTL使用引用(references)来在web site内嵌套动态内容。一个变量就是一种类型的reference。变量是某种类型的refreence。它可以指向java代码中定义的对象,或者在当前页面内使用VTL statement定义的变量。下面是一个VTL statement的例子,它可以被嵌套到HTML代码中:
1
|
#set ( $a = “Velocity” )
|
和所有的VTL statement一样,这个statement以#字符开始并且包含一个directive:set。当一个在线用户请求你的页面时,Velocity Templating Engine将查询整个页面以便发现所有#字符,然后确定哪些是VTL statement,哪些不需要VTL作任何事情。 #字符后紧跟一个directive:set时,这个set directive 使用一个表达式 (使用一对圆括号`(` , `)` 封闭) 分配一个值给变量$a。变量被列在左边,而它的值被列在右边,最后他们之间使用=号分割。
记住以下的规则: 使用$字符开始的references用于得到什么;使用#字符开始的directives用于作些什么。
一旦某个变量被分配了一个值,那么你就可以在HTML文件的任何地方引用它。在下面的例子中,一个值被分配给$foo变量,并在其后被引用。
1
2
3
4
5
6
|
<
html
>
<
body
>
#set ( $foo = “Velocity” )
Hello $foo World!
</
body
>
</
html
>
|
上面的实现结果是在页面上打印“Hello Velocity World!”
为了使包含VTL directives的statement更具有可读性,我们建议在新行开始每个VTL statement,尽管你不是必须这么作。Set directive将在后面详细描述。
注释
单行注释:
1
|
## This is a single line comment.
|
1
2
3
4
5
|
#*
Thus begins a multi-line comment. Online visitors won’t
see this text because the Velocity Templating Engine will
ignore it.
*#
|
文档格式:
1
2
3
4
5
6
7
8
|
#**
This is a VTL comment block and
may be used to store such information
as the document author and versioning
information:
@version 5
@author
*#
|
References
在VTL中有三种类型的references:变量(variables)、属性(properties)、方法(methods)。
作为一个使用VTL的页面设计者,你和你的工程师必须就references的名称达成共识,以便你可以在你的template中使用它们。
Everything coming to and from a reference被作为一个String对象处理。如果有一个对象$foo是一个Integer对象,那么Velocity将调用它的toString()方法将这个对象转型为String类型。变量
格式要求同java。
属性
例子:
1
2
|
$customer.Address
$purchase.Total
|
方法
一个方法就是被定义在java中的一段代码,并且它有完成某些有用工作的能力,例如一个执行计算和判断条件是否成立、满足等。方法是一个由$开始并跟随VTL标识符组成的References,一般还包括一个VTL方法体。例如:
1
2
3
4
|
$customer.getAddress()
$purchase.getTotal()
$page.setTitle( “My Home Page” )
$person.setAttributes( [“Strange”, “Weird”, “Excited”] )
|
前两个例子$customer.getAddress()和$purchase.getTotal()看起来挺想上面的属性$customer.Address 和 $purchase.Total。如果你觉得他们之间有某种联系的话,那你是正确的;因为VTL属性可以作为VTL方法的缩写。$customer.Address属性和使用$customer.getAddress()方法具有相同的效果。如果可能的话使用属性的方式是比较合理的。属性和方法的不同点在于你能够给一个方法指定一个参数列表。
Velocity利用了很多java规范以方便了设计人员的使用。例如
$foo.getBar() 等同于 $foo.Bar 等同于 ${foo.Bar}
$data.getUser(“jon”) 等同于 $data.User(“jon”) 等同于 ${data.User("join")}
$data.getRequest().getServerName() 等同于 $data.Request.ServerName 等同于 ${data.Request.ServerName}
需要明确的是VTL中不会将reference解释为对象的实例变量。例如:$foo.Name将被解释为Foo对象的getName()方法(假如$foo所引用的对象不是Hashtale对象),而不是Foo对象的Name实例变量。
正式reference标记
reference的正是格式如下:
1
2
3
|
${mudSlinger} ##变量
${customer.Address} ##属性
${purchase.getTotal()} ##方法
|
但非正式格式更常见,但是有时还是使用正式格式比较好。例如:你希望通过一个变量$vice来动态的组织一个字符串:
1
|
Jack is a $vicemaniac.
|
本来用意是是引用变量$vice,现在却变成了$vicemaniac,这样Veloctiy就不知道您到底要什么了。所以在这种情况下应该使用正式格式书写:
1
|
Jack is a ${vice}maniac
|
现在Velocity知道你希望引用的变量是$vice而不是$vicemaniac, 模板被渲染后的结果为:
Quiet reference notation
关于空值(null)的处理
当一个变量没有被定义或为空值(null) , velocity模板会将该变量名连同美元符号一起输出。考虑如下的html片段:
1
|
<
input
type=”text” name=”email” value=”$email” />
|
当页面的form被初始加载时,变量$email还没有值,这时你肯定是希望它能够显示一个空字符串("")来代替$email这样的字符串,那么就需要使用quiet reference notation,即$!标记
1
|
<
input
type=”text” name=”email” value=”$!email”/>
|
当然 使用正式的quiet格式会更好:
1
|
<
input
type=”text” name=”email” value=”$!{email}”/>
|
关于特殊字符的处理
Velocity使用特殊字符$和#来帮助它工作,所以如果要在template里使用这些特殊字符要格外小心。
在VTL中, 像$2.5这样的标识符不会被认为是一个reference,因为VTL中的reference总是以一个大写或者小写的字母开始.
VTL中使用“\”作为转义符。
例如:
1
2
3
4
5
|
#set( $email = “foo” )
$email
\$email
\\$email
\\\$email
|
将被渲染为:
foo
\foo
如果email变量没有被定义则
1
2
3
4
|
$email
\$email
\\$email
\\\$email
|
将被渲染为:
指令(Directives)
reference允许设计者使用动态的内容,而directive使得你可以控制显示逻辑,从而达到期望的显示效果。
#set 指令
#set directive被用于设置一个reference的值。例如:
1
2
|
#set ( $primate = “monkey” )
#set ( $customer.Behavior = $primate )
|
赋值左侧的(LHS)必须是一个变量或者属性reference。右侧(RHS)可以是以下类型中一种:
变量引用(variable reference)
字符串字面值(String literal)
属性引用(property reference)
方法调用(method reference)
数字字面值( number literal)
数组列表(Array List)
下面是应用各种类型的RHS的例子:
1
2
3
4
5
6
|
#set ( $monkey = $bill ) ## 变量引用(variable reference)
#set ( $monkey.Friend = “monica” ) ##字符串字面值(String literal)
#set ( $monkey.Blame = $whitehouse.Leak )## 属性引用(property reference)
#set ( $monkey.Plan = $spindoctor.weave($web) )##方法调用(method reference)
#set ( $monkey.Number = 123 ) ## 数字字面值( number literal)
#set ( $monkey.Say = [“Not”, $my, “fault”] ) ##数组列表(Array List)
|
注意:最后一个例子的取值方法为:$monkey.Say.get(0)
RHS也可以是一个简单的算术表达式:
1
2
3
4
|
#set ( $value = $foo + 1 )
#set ( $value = $bar -1 )
#set ( $value = $foo * $bar )
#set ( $value = $foo / $bar )
|
如果你的RHS是一个null,VTL的处理将比较特殊:它将指向一个已经存在的reference,这对初学者来讲可能是比较费解的。例如:
1
2
3
4
|
#set ( $resut = $query.criteria(“name”) )
The result of the first query is $result
#set ( $resut = $query.criteria(“address”) )
The result of the second query is $result
|
如果$query.criteria(“name”)返回一个“bill”,而$query.criteria(“address”)返回的是null,则显示的结果如下:
The result of the first query is bill
The result of the first query is bill
再看一个例子:
1
2
3
4
5
6
7
|
#set( $criteria = ["name", "address"] )
#foreach( $criterion in $criteria )
#set( $result = $query.criteria($criterion) )
#if( $result )
Query was successful
#end
#end
|
打印的结果将显示两次查询结果都成功了。
为什么会出现这种现象呢?其实当某个变量被赋值后,它就被保存到Velocity的context(added to the context),并且buhui不能被设置回null(removed from the context)。
为了解决以上问题我们可以通过预先定义的方式:
1
2
3
4
5
6
7
8
|
#set( $criteria = [“name”, “address”] )
#foreach( $criterion in $criteria )
#set( $result = false )
#set( $result = $query.criteria( $criterion ) )
#if( $result )
Query was successful
#end
#end
|
关于 字符串字面值(String Literals )
当你使用#set 指令时,如果把字符串字面值(String literal)封闭在一对双引号内, 比如
1
2
3
4
|
#set ( $directoryRoot = “www” )
#set ( $templateName = “index.vm” )
#set ( $template = “$directoryRoot/$tempateName” )
$template
|
则渲染的结果为
www/index.vm
但是,当字符串字面值(String Literal)被封装在单引号内时,它将不被解析:
1
2
3
4
|
#set ( $foo = “bar” )
$foo
#set ( $blargh = ‘$foo’ )
$blargh
|
结果:
bar
$foo
这个特性可以通过修改velocity.properties文件的属性设置
stringliterals.interpolate = false
来改变上面的特性失效。
当一个web页面被生成时如果使用了Velocity的#if 指令,那么当条件成立的时,执行相应的代码。例如:
1
2
3
|
#if ( $foo )
<
strong
>Velocity!</
strong
>
#end
|
上例中的条件语句将在满足以下两种条件之一时成立:
- $foo是一个boolean型的变量,且它的值为true
- $foo变量的值不为null
#elseif和#else元素可以同#if一同使用。例如:
1
2
3
4
5
6
7
8
9
|
#if( $foo <
10
)
<strong> Go North </
strong
>
#elseif( $foo == 10 )
<
strong
> Go East </
strong
>
#elseif( $foo == 6 )
<
strong
> Go South </
strong
>
#else
<
strong
> Go West </
strong
>
#end
|
注意,这里的Velocity的数字是作为Integer来比较的, 其他类型的对象将使得条件为false,但是与java不同的是Velocity使用“==”来比较两个值,而且velocity要求等号两边的值类型相同。
关系、逻辑运算符
Velocity中使用双等号(==) 判断两个变量的关系。例如:
1
2
3
4
5
6
7
|
#set ( $foo = “deoxyribonucleic acid” )
#set ( $bar = “ribonucleic acid” )
#if ( $foo == $foo )
In this case it’s clear they aren’t equivalent.So…
#else
They are not equivalent and this will be the output.
#end
|
Velocity有AND、OR和NOT逻辑运算符。例子:
1
2
3
4
|
## logical AND
#if( $foo && $bar )
<
strong
> This AND that </
strong
>
#end
|
1
2
3
4
|
## logical OR
#if ( $foo || $bar )
<
strong
>This OR That </
strong
>
#end
|
1
2
3
4
|
##logical NOT
#if ( !$foo )
<
strong
> NOT that </
strong
>
#end
|
循环(#foreach)
例子:
1
2
3
4
5
|
<
ul
>
#foreach ( $product in $allProducts )
<
li
> $product </
li
>
#end
</
ul
>
|
每次循环都从$allProducts中取出一个值赋给$product变量。 $allProducts可以是一个Vector、Set或者Array。分配给$product的值是一个java对象,并且可以通过变量被引用。 如果$product是一个java的Product类,并且这个产品的名字可以通过调用他的getName()方法得到。 现在我们假设$allProducts是一个Hashtable,如果你希望得到它的key应该像下面这样:
1
2
3
4
5
|
<
ul
>
#foreach ( $key in $allProducts.keySet() )
<
li
>Key: $key -> Value: $allProducts.get($key) </
li
>
#end
</
ul
>
|
Velocity还特别提供了得到循环次数的方法 :
1
2
3
4
5
|
<
table
>
#foreach ( $customer in $customerList )
<
tr
><
td
>$velocityCount</
td
><
td
>$customer.Name</
td
></
tr
>
#end
</
table
>
|
$velocityCount变量的名字是Velocity内置的变量。你也可以通过修改velocity.properties文件来改变它。默认情况下,计数从“1”开始,但是你可以在velocity.properties设置它是从“1”还是从“0”开始。下面的设置将velocityCount的名字改为loopCount, 循环计数从0开始:
1
2
3
4
5
6
7
|
# Default name of loop counter
# variable reference
directive.foreach.counter.name = velocityCount
# Default starting value of the loop
# counter variable reference
directive.foreach.counter.initial.value = 1
|
#include指令
#include指令允许模板设计者引入本地文件, 被引入文件的内容将不会通过模板引擎被render。为了安全的原因,被引入的本地文件只能在TEMPLATE_ROOT目录下。
#include指令的用法很简单:
1
|
#inclued ("one.txt")
|
如果您需要引入多个文件,可以用逗号分隔就行:
1
|
#include ("one.gif", "two.txt", "three.htm")
|
在括号内可以是文件名,可以使用变量的:
1
|
#inclue ("greetings.txt", $seasonalstock )
|
#parse指令
#parse 指令允许模板设计者一个包含VTL的本地模板文件, Velocity将解析其中的VTL并进行渲染。用法
#parse指令用法:
1
|
#parse("me.vm")
|
和#include一样,#parse指向的模板都必须包含在TEMPLATE_ROOT目录下, 但#parse只能指定单个对象。
#parse是可以递归调用的,例如在foo.vmz中有如下内容:
1
2
3
4
|
Count down.
#set ( $count = 8 )
#parse ( “parsefoo.vm” )
All done with dofoo.vm!
|
那么在parsefoo.vm模板中,你可以包含如下VTL:
1
2
3
4
5
6
7
|
$count
#set ( $count = $count – 1 )
#if ( $count > 0 )
#parse( “parsefoo.vm” )
#else
All done with parsefoo.vm!
#end
|
渲染后的结果为:
Count down.
8
7
6
5
4
3
2
1
0
All done with parsefoo.vm!
All done with dofoo.vm!
你可以通过修改velocity.properties文件的parse_direcive.maxdepth属性值来控制嵌套#parse的层数,默认值是10。
#stop指令
#stop指令允许模板设计者停止执行模板引擎并返回。#stop对调试很有帮助。#stop用法
1
|
#stop
|
Velocity的 宏(#macro)
#macro指令用于定义Velocity的宏。 宏可以定义一段可重用的VTL template。例如:
1
2
3
|
#macro ( d )
<
tr
><
td
></
td
></
tr
>
#end
|
上面的例子中定义了一个Velocity的宏, 然后你可以这样来使用它:
1
|
#d()
|
当你的template被调用时,Velocity将用<tr><td></td></tr>替换为#d()。
每个Velocity的宏可以拥有任意数量的参数。虽然定义时可以随意设置参数数量,但是调用这个Velocimacro时必须指定正确的参数。下面是一个拥有两个参数的宏,其中一个参数是color,另一个参数是array:
1
2
3
4
5
6
7
8
9
10
|
#macro ( tablerows $color $somelist )
#foreach ( $something in $somelist )
<
tr
><
td
bgcolor=$color>$something</
td
</tr>
#end
#set ( $greatlakes = [ “Superior”, “Michigan”, “Huron”, “Erie”, “Ontario” ] )
#set ( $color = “blue” )
<
table
>
#tablerows( $color $greatlakes )
</
table
>
|
渲染后:
<table>
<tr><td bgcolor=” blue”> Superior </td></tr>
<tr><td bgcolor=” blue”> Michigan </td></tr>
<tr><td bgcolor=” blue”> Huron </td></tr>
<tr><td bgcolor=” blue”> Erie </td></tr>
<tr><td bgcolor=” blue”> Ontario </td></tr>
</table>
Velocity的宏可以在Velocity模板内实现行内定义(inline)。 这就意味着同一个web site内的其他Velocity模板不可以获得该宏的定义。
定义一个可以被所有模板共享的Velocimacro显然是有很多好处的:它减少了在一大堆模板中重复定义的数量、节省了工作时间、减少了出错的几率、保证了单点修改。
实际上,上面定义的#tablerows( $color $list ) 宏已被定义在一个Velocity宏模板库(在velocity.properties中定义)里,所以这个macro可以在任何规范的模板中被直接调用。
Velocity的宏可以使用以下任何元素作为参数:
- 任何以$开头的reference
- 字符串字面值(String literal)
- 数字字面值(Number literal)
- 整数范围(IntegerRange):[1….3] , [$foo….$bar]
- 数组列表(Array List):[“a”,”b”,”c”]
- 布尔字面值(Boolean Literal):true、false
1
2
3
4
|
#macro ( callme $a )
$a $a $a
#end
#callme( $foo.bar() )
|
执行的结果是:reference $foo的bar()方法被执行了三次。 如果你不需要这样的特性, 可以通过以下方法:
1
2
|
#set ( $myval = $foo.bar() )
#callme ( $myval )
|
- velocimcro.library属性:指定自己的模板库,多个模板库以逗号分隔。默认情况下,velocity查找唯一的一个库:VM_global_library.vm
- velocimacro.permissions.allow.inline属性:是否允许开发者在普通模板内定义Velocity宏。ho
- velocimacro.permissions.allow.inline.replace.global属性: 是否允许设计者使用本地的inline的 宏替代全局的宏(全局的宏是指在velocimacro.library属性中指定的文件内定义的宏)。默认情况下,此值为false。这样就阻止本地的宏覆盖全局的。
- velocimacro.permissions.allow.inline.local.scale属性: inline定义的宏是否仅仅在被定义的template内可见. 默认是false。 换句话说,如果这个属性设置为true,一个inline定义的宏只能在定义它的template内使用。
- velocimacro.context.localscope属性: 默认值为false。当设置为true时,任何在宏内通过#set()对context的修改被认为是针对此宏的本地设置,而不会永久的影响内容。
- velocimacro.library.autoreload属性: 控制宏库的自动加载。默认是false。当设置为ture时,对于一个宏的调用将自动检查原始库是否发生了变化,如果变化将重新加载它。这个属性使得你可以不用重新启动servlet容器而达到重新加载的效果,就像你使用regular模板一样。这个属性可以使用的前提就是resource loader缓存是off状态(file.resource.loader.cache = false)。注意这个属性实际上是针对开发而非产品的。
1
2
3
4
5
6
7
8
|
## #include( “a.txt” ) renders as <
ontents
of a.txt>(注释行)
#include( “a.txt” )
## \#include( “a.txt” ) renders as \#include( “a.txt” )
\#include( “a.txt” )
## \\#include ( “a.txt” ) renders as \<
contents
of a.txt>
\\#include( “a.txt” )
|
1
2
3
|
#if ( $jazz )
Vyacheslav Ganelin
#end
|
1
2
3
|
\#if ( $jazz )
Vyacheslav Ganelin
\#end
|
1
2
3
|
\\#if ( $jazz )
Vyacheslav Ganelin
\\#end
|
1
2
3
4
|
#set ( $imperial = [ “Munetaka”, “Koreyasu”, “Hisakira”, “Morikune” ] )
#foreach ( $shogun in $imperial )
$shogun
#end
|
1
|
Send me #set($foo = [“$10 and”,”a cake”])#foreach($a in $foo)$a #end please.
|
1
2
3
4
5
6
|
Send me
#set ( $foo = [“$10 and “,”a cake”] )
#foreach ( $a in $foo )
$a
#end
please.
|
1
2
3
4
|
Send me
#set($foo = [“$10 and “,”a cake”])
#foreach ($a in $foo )$a
#end please.
|
- 在模板中可以使用Velocity内建的算术函数,如:加、减、乘、除
1
2
3
4
|
#set ( $foo = $bar + 3 )
#set ( $foo = $bar - 4 )
#set ( $foo = $bar * 6 )
#set ( $foo = $bar / 2 )
|
1
|
#set ( $foo = $bar % 5 )
|
1
|
[n..m]
|
1
2
3
|
#foreach ( $foo in [1..5] )
$foo
#end
|
Second example:
1
2
3
|
#foreach ( $bar in [2..-2] )
$bar
#end
|
1
2
3
4
|
#set ( $arr = [0..1] )
#foreach ( $i in $arr )
$i
#end
|
1
|
[1..3]
|
注意:range operator只在#set和#foreach中有效。
Advanced Issue:Escaping and!
1
|
#set ( $foo = “bar” )
|
- Can I user a directive or another VM as an argument to a VM? For example, #center ( #bold( “hello” ) )
1
2
|
#set ( $stuff = "#bold( 'hello' )" )
#center ( $stuff )
|
1
|
#center ("#bold('hello')")
|
1
2
3
4
5
6
7
8
9
10
11
|
#macro ( inner $foo )
inner : $foo
#end
#macro ( outer $foo )
#set ( $bar = "outerlala" )
outer : $foo
#end
#set ( $bar = 'calltimelala' )
#outer( "#inner($bar)" )
|
1
2
3
4
5
6
|
#macro ( foo $color )
<
tr
bgcolor = $color ><
td
>Hi</
td
></
tr
>
<
tr
bgcolor = $color ><
td
>There</
td
></
tr
>
#end
#foo ( $bar.rowColor() )
|
1
2
|
#set ( $color = $bar.rowColor() )
#foo ( $color )
|
- can I register velocimacros via #parse()?
- What is velocimacro autoreloading?
1
2
3
|
#set ( $size = “Big” )
#set ( $name = “Ben” )
The clock is $size$name.
|
1
2
3
4
|
#set ( $size = “Big” )
#set ( $name = “Ben” )
#set ( $clokc = “$size$name” )
The clock is $clock.
|
1
2
3
4
|
#set ( $size = "Big" )
#set ( $name = "Ben" )
#set ( $clock = "${size}Tall$name" )
The clock is $clock.
|