Velocity语法大全
1. 基本语法
1.1. #
#
用来标识Velocity的脚本语句,包括#set
、#if
、#else
、#end
、#foreach
、#end
、#iinclude
、#parse
、#macro
等。
例如:
#if($info.imgs)
<img src="$info.imgs" border=0>
#else
<img src="noPhoto.jpg">
#end
1.2. $
$
用来标识一个对象(或理解为变量)。例如:$i
、$msg
、$TagUtil.options(...)
等。
1.3. {}
{}
用来明确标识Velocity变量。
比如在页面中,页面中有一个$someonename
,此时,Velocity将把someonename
作为变量名,若我们程序是想在someone
这个变量的后面紧接着显示name
字符,则上面的标签应该改成${someone}name
。
1.4. !
!
用来强制把不存在的变量显示为空白。
如当页面中包含$msg
,如果msg
对象有值,将显示msg
的值,如果不存在msg
对象,则在页面中将显示$msg
字符。这是我们不希望的,为了把不存在的变量或变量值为null
的对象显示为空白,则只需要在变量名前加一个!
号即可。例如:$!msg
。
2. 脚本语法
2.1. 注释
单行:
## XXX
多行:
#*
xxx
xxxx
xxxxxxxxxxxx
*#
2.2. 变量声明
语法:
#set ($var=XXX)
例子:
#set ($i=0)
#foreach($info in $list)
序号:$i
#set($i=$i+1)
#end
2.3. 条件语句if
语法:
#if($foo)
#elseif()
#else
#end
例如:
#if($foo)
<strong>Velocity!</strong>
#end
当$foo
不为null
或为Boolean
对象的true
值执行。
2.4. 逻辑运算符
==
、&&
、||
、!
2.5. 循环语句foreach
语法:
#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