一、Velocity Template Language (VTL)介紹
1、#set
用來定義頁面內使用的變量。例如:
#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"] ) ## ArrayList
#set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"}) ## Map
2、comment
註釋語法爲# ,#* *#,#** *#
3、References
References有三類,分別是variables, properties and methods,分別舉例如下:
variables:
$foo
推薦寫法 $!foo ,值不存在的時候,會用空字符串替代
properties :
$customer.Address
methods:
$customer.getAddress()
$purchase.getTotal()
$page.setTitle( "My Home Page" )
$person.setAttributes( ["Strange", "Weird", "Excited"] )
4、If / ElseIf / Else
邏輯分支判斷,例如
#if( $foo < 10 )
<strong>Go North</strong>
#elseif( $foo == 10 )
<strong>Go East</strong>
#elseif( $bar == 6 )
<strong>Go South</strong>
#else
<strong>Go West</strong>
#end
5、#foreach
一下是該標籤的常用代碼實例片段,
一般的例子
<ul>
#foreach( $product in $allProducts )
<li>$product</li>
#end
</ul
Map循環的例子
<ul>
#foreach( $key in $allProducts.keySet() )
<li>Key: $key -> Value: $allProducts.get($key)</li>
#end
</ul>
通過$foreach.count獲取循環計數器,類似的還有($foreach.index,$foreach.last, $foreach.first等)
<table>
#foreach( $customer in $customerList )
<tr><td>$foreach.count</td><td>$customer.Name</td></tr>
#end
</table>
通過$foreach.hasNext來判斷是否是最後一次循環
#foreach( $customer in $customerList )
$customer.Name#if( $foreach.hasNext ),#end
#end
通過#break來中斷循環
## list first 5 customers only
#foreach( $customer in $customerList )
#if( $foreach.count > 5 )
#break
#end
$customer.Name
#end
6、#include
該標籤用來引入一個本地文件,引入的時候是靜態引入,不會被Velocity Engine進行render.並且基於安全原因,被引入文件最好被放在TEMPLATE_ROOT下
簡單例子如下:
#include( "one.txt" )
如果有多個文件需要引入,可以用逗號分隔
#include( "one.gif","two.txt","three.htm" )
同時引入兩個文件,其中一個文件用變量來指定路徑以及文件名
#include( "greetings.txt", $seasonalstock )
7、#parse
對比#include,該標籤可以包含VTL,可以被Velocity Engine進行render。但是隻接受一個參數
8、#stop
該標籤後面的html將不進行解析和展現
9、#evaluate
對字符串進行render,感覺用處不大
10、#define
相當於一個“函數”,定義一個代碼塊,可在後續進行引用,例如:
#define($myfunc) $who,hello!#end
#set($who="kongxuan")
$myfunc
運行結果:
kongxuan,hello!
11、#macro
宏調用,是一個非常重要的指令。用來抽取頁面中重複的VTL代碼片段。
#macro( tablerows $color $somelist )
#foreach( $something in $somelist )
<tr><td bgcolor=$color>$something</td></tr>
#end
#end
#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#set( $color = "blue" )
<table>
#tablerows( $color $greatlakes )
</table>
注意:宏可以寫在文件VM_global_library.vm裏面,resource根目錄下,且需要新增配置項:
在velocity.properties中新增配置項velocimacro.library=VM_global_library.vm
二、velocity配置項
(待續)