`

velocity简明手册

阅读更多

1.声明变量
#set($var = XXX)
右边可以是以下的内容
Variable reference
String literal
Property reference
Method reference
Number literal #set ($i=1)
ArrayList #set ($arr=["yt1","t2"])
技持算术运算符

2、注释:
单行## XXX
多行#* xxx
xxxx
xxxxxxxxxxxx*#

3、变量 Variables
以 "$" 开头,第一个字符必须为字母。character followed by a VTL Identifier. (a .. z
or A .. Z).
变量可以包含的字符有以下内容:
alphabetic (a .. z, A .. Z)
numeric (0 .. 9)
hyphen ("-")
underscore ("_")

4、Properties
$Identifier.Identifier
$user.name
hashtable user中的的name值.类似:user.get("name")

5、Methods
object user.getName() = $user.getName()

6、Formal Reference Notation
用{}把变量名跟字符串分开


#set ($user="csy"}
${user}name
返回csyname

$username
$!username
$与$!的区别
当找不到username的时候,$username返回字符串"$username",而$!username返回空字符串""

7、双引号 与 引号
#set ($var="helo")
test"$var" 返回testhello
test'$var' 返回test'$var'
可以通过设置 stringliterals.interpolate=false改变默认处理方式

8、条件语句
#if( $foo )
<strong>Velocity!</strong>
#end
#if($foo)
#elseif()
#else
#end
当$foo为null或为Boolean对象的false值执行.

9、逻辑运算符:== && || !

10、循环语句#foreach($var in $arrays ) // 集合包含下面三种Vector, a Hashtable or an Array
#end
#foreach( $product in $allProducts )
<li>$product</li>
#end

#foreach( $key in $allProducts.keySet() )
<li>Key: $key -> Value: $allProducts.get($key)</li>
#end

#foreach( $customer in $customerList )
<tr><td>$velocityCount</td><td>$customer.Name</td></tr>
#end

11、velocityCount变量在配置文件中定义
# Default name of the loop counter
# variable reference.
directive.foreach.counter.name = velocityCount
# Default starting value of the loop
# counter variable reference.
directive.foreach.counter.initial.value = 1

12、定义宏Velocimacros ,相当于函数 支持包含功能
#macro( d )
<tr><td></td></tr>
#end
调用
#d()

13、带参数的宏
#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
<tr><td bgcolor=$color>$something</td></tr>
#end
#end
调用
# tablerows (“red” “…”)

项目开发中需要注意到的要点:
1. vm中显示变量,一律加!和{},如:$!{userName}、$!{userVO.name}、$!{userVO.getName()}、$!{userMap.get(“Bob”)}
2. 合并字符串
如果变量是字符串或数值型,如 #set($user = “Tester”),则应为 “welecom$!{user}”,而不是 “welcome” + $user
3. #if($var)条件判断,当且仅当:$var存在(如果$var是Boolean/boolean型,还必须$var的值为Boolean.true/true)时,条件才成立
4. #foreach()循环的时候,有个系统变量$velocityCount可直接使用,不必自己设定额外的计数器
5. 比较字符串相等,#if($var == “test”)   #if(“test”.equals($var))均可,
6. vm中生成URL
#set($userName = “Bob”)
“$offerModule.setTarget('modifySingleOffer.vm').addQueryData(‘userName’, $userName).fork()”
“$offerModule.setTarget('modifySingleOffer.vm').addQueryData(‘userName’, ‘Bob’).fork()”
目标大致如:http://127.0.0.1/offer/modifySingleOffer.htm?userName=Bob
7. vm中调用control
$control.setTemplate("home:pageNavigator.vm").setParameter("position", "top").setParameter("pageList", $pageList)
8.其它可能会被使用到的,如定义自己的宏(定义和修改宏,需要重新启动应用服务器才生效)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics