基本語法¶
#set ($var=XXX)
左邊可以是以下的內容:
- Variable reference
- String literal
- Property reference
- Method reference
- Number literal #set ($i=1)
- ArrayList #set ($arr=["yt1","t2"])
- 算術運算符
- References 引用的類型
單行:
## this is a comment
多行:
#* this line
and this line
and this line, are comments...*#
變量 Variables¶
以 "$" 開頭,第一個字符必須為字母。character followed by a VTL Identifier. (a .. z or A .. Z).
變量可以包含的字符有以下內容:
- alphabetic (a .. z, A .. Z)
- numeric (0 .. 9)
- hyphen ("-")
- underscore ("_")
Properties¶
$Identifier.Identifier
$user.name
hashtable user中的的name值.類似:user.get("name")
h2、Methods
object user.getName() = $user.getName()
h2、Formal Reference Notation
用{}把變量名跟字符串分開。如
#set ($user="csy"}
${user}name
返回csyname
$與$!的區別¶
當找不到username的時候,$username返回字符串"$username",而$!username返回空字符串""
雙引號 與 引號¶
#set ($var="helo")
則 test"$var" 返回testhello,test'$var' 返回test'$var'。
可以通過設置 stringliterals.interpolate=false改變默認處理方式
條件語句¶
#if( $foo )
<strong>Velocity!</strong>
#end
#if($foo)
#elseif()
#else
#end
當$foo為null或為Boolean對象的false值執行.
邏輯運算符:¶
== && || !
循環語句¶
#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
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
包含文件¶
#include( "one.gif","two.txt","three.htm" )
Parse導入腳本¶
#parse("me.vm" )
#stop 停止執行并返回¶
定義宏¶
Velocimacros, 相當于函數支持包含功能:
#macro( d )
<tr><td></td></tr>
#end
調用
#d()
帶參數的宏¶
#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
<tr><td bgcolor=$color>$something</td></tr>
#end
#end
Range Operator¶
#foreach( $foo in [1..5] )
與struts2的整合¶
模板裝載位置(按順序依次搜索)¶
- Web application 應用程序路徑,會覆蓋掉類路徑下的同名配置文件;
- Class path 類路徑,一般為缺省模板的配置,公共模板位置;
數據來源(按順序依次搜索)¶
- The value stack
- The action context
- Built-in variables
Struts2-Velocity集成的一些隱含變量¶
- stack - ValueStack自身。調用方式:${stack.findString('ognl expr')}
- action - 最新操作的action
- reponse
- request
- session
- applicaion - 獲得servlet的環境
- base - 請求環境的路徑
Velocity Result 輸出模板¶
模擬jsp執行環境,使用velocity的模板直接顯示到servelet的輸出流。
location - 模板位置,沒有其它參數時的缺省配置。
parse - 默認true ,false將不解析Ognl expressions.
配置范例:
<result name="success" type="velocity">
<param name="location">foo.vm</param>
</result>
等價于以下的配置方式:
<result name="success" type="velocity">
foo.vm
</result>
Velocity語法¶
http://blog.csdn.net/alexwan/archive/2007/10/29/1853285.aspx
Struts 與 Velocity 的集成¶
http://www.ibm.com/developerworks/cn/java/j-sr1.html
posted on 2009-07-02 09:38
xiaoxinchen 閱讀(161)
評論(0) 編輯 收藏