1. 程式人生 > >velocity(vm)模板引擎學習介紹及語法

velocity(vm)模板引擎學習介紹及語法

velocityfreemaker、jstl並稱為java web開發三大標籤技術,而且velocity在codeplex上還有.net的移植版本NVelocity,(注:castle團隊在github上也維護了一個版本)對於使用異構技術的團隊(即要搞.NET又要搞JAVA),總是希望找一種通用的技術,相容所有技術平臺,以便降低學習成本,無疑velocity是一種值得考慮的選擇。

一、與strtus2的整合

複製程式碼
 1         <dependency>
 2             <groupId>org.apache.velocity</groupId
> 3 <artifactId>velocity</artifactId> 4 <version>1.7</version> 5 </dependency> 6 7 <dependency> 8 <groupId>org.apache.velocity</groupId> 9 <artifactId>velocity-tools</artifactId
> 10 <version>2.0</version> 11 </dependency>
複製程式碼

pom.xml中加入這二項即可,其它不用刻意配置。struts2同時支援jstl(.jsp)、velocity(.vm)、freemaker(.ftl)三種模板。

二、定義變數

1   #set($awbpre='112')
2   #set($awbno='89089011')
3   #set($airwayBillNo=$awbpre+' - '+$awbno)
4   $awbpre - $awbno <br/>
5
$airwayBillNo

velocity的語法符號大概分二類,一類用#開頭,代表控制符號,#set表示定義變數,另一類用$開頭,通常用於顯示變數,上面的示例定義了三個變數:
awbpre 值為'112',awbno值為'89089011',airwayBillNo值為 '112 - 89089011'

第4,5二行輸出內容

三、遍歷陣列

1   #set($list = ["CTU", "SHA", "LAX"])
2   #foreach ($item in $list)
3      $velocityCount . $item <br/>
4   #end

解釋:定義了一個數組,然後遍歷輸出,其中velocityCount為索引變數

四、遍歷HashTable

1   #foreach($key in $table.keySet())
2     $key -> $table.get($key)<br/>
3   #end


五、判斷是否為空

複製程式碼
1       #if($null.isNull($orderList.orders) || $orderList.orders.size()==0)
2           訂單列表為空
3       #else
4           訂單列表:<br/>
5           #foreach ($order in $orderList.orders)
6               $velocityCount: $order.id / $order.clientName / $order.amount / $order.createTime<br/>
7           #end
8       #end
複製程式碼

上面是判斷集合是否為空的,如果判斷單個物件是否為空,參考下面這樣:

複製程式碼
 1     #if($(orderDto))
 2         訂單物件有值
 3     #else
 4         訂單物件為空
 5     #end
 6 
 7     #if(!$(orderDto))
 8         訂單物件為空
 9     #else
10         訂單物件有值
11     #end
複製程式碼


六、巨集示例

巨集可以理解為“函式”,定義一個巨集即相當於定義一個子函式,呼叫巨集,即為呼叫子函式

複製程式碼
 1     #macro(renderOrderList $orders)
 2         <table border="1">
 3           <tr>
 4               <th>Id</th>
 5               <th>ClientName</th>
 6               <th>Amount</th>
 7               <th>CreateTime</th>
 8           </tr>
 9           #foreach($o in $orders)
10             <tr><td>$o.id</td><td>$o.clientName</td><td>$o.amount</td><td>$o.createTime</td></tr>
11           #end
12         </table>
13     #end
14 
15     #renderOrderList($orderList.orders)
複製程式碼


七、數值、日期格式化

複製程式碼
1     $order.createTime<br/>
2     $date.year - $date.month - $date.day <br/>
3     $date.format('yyyy-MM-dd HH:mm:ss',$order.createTime,$locale)<br/>  
4     $date.format('MMMdd',$order.createTime,$locale)<br/>    
5     $convert.toLocale("en_US") <br/>
6     $date.format('MMM,dd',$order.createTime,$convert.toLocale("en_US"))<br/>
7     $date.format('yyyy-MM-dd',$order.createTime,$locale)<br/>
8     $order.amount<br/>
9     $number.format('0.00',$order.amount)<br/>
複製程式碼
NumberTool中還有貨幣格式化的功能:$number.format("currency", $agentBillDto.feeTotal)

要使用格式化功能,需要加一點配置,struts.xml檔案中加一行

<constant name="struts.velocity.toolboxlocation" value="WEB-INF/classes/toolbox.xml" />

然後在toolbox.xml中,參考下面的內容:

複製程式碼
 1 <?xml version="1.0" encoding="UTF-8"?> 
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
 4     "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
 5 <toolbox>
 6     <tool>
 7         <key>number</key>
 8         <scope>application</scope>
 9         <class>org.apache.velocity.tools.generic.NumberTool</class>
10     </tool>
11     <tool>
12         <key>date</key>
13         <scope>application</scope>
14         <class>org.apache.velocity.tools.generic.DateTool</class>
15     </tool>
16     <tool>
17         <key>text</key>
18         <scope>request</scope>
19         <class>org.apache.velocity.tools.struts.MessageTool</class>
20     </tool>
21     <tool>
22         <key>convert</key>
23         <scope>application</scope>
24         <class>org.apache.velocity.tools.generic.ConversionTool</class>
25     </tool>
26 </toolbox>
複製程式碼

這些XXXTool其實是一個很好的例子,因為velocity的vm檔案裡不能直接寫java程式碼,如果我們想擴充套件一些常用方法,可以將一些常用方法寫成XXXTool工具類,然後在toolbox中註冊即可。

八、國際化

1  當前語言環境:$locale <br/>   
2  #stext("name=%{getText('appName')}")

雖然Velocity-Tools 2.0中提供了MessageTool,但是我一直沒嘗試成功,只能藉助struts2本身的標籤來處理了。struts2中首先得定義國際化資原始檔的BaseName

1 <constant name="struts.custom.i18n.resources" value="message"></constant>

然後在classPath目錄下,放二個檔案message_zh_CN.properties、message_en_US.properties,裡面放一個appName=XXX的內容,用#stext就能取到國際化的內容了

九、使用struts2標籤

雖然有了velocity基本上可以告別struts2的那一堆tags,但是如果懷念struts2裡的標籤,也可以繼續使用,方法:以“#s”開頭就行了,參考下面的示例:

1 #stextarea ("label=Biography" "name=bio" "cols=20" "rows=3") <br/>
2 #sselect("label=Favourite Color" "list={'Red', 'Blue', 'Green'}" "name=favouriteColor" "emptyOption=true" "headerKey=None" "headerValue=None")    <br/> 

十、內建物件

1 $request<br/>
2 name = $request.getParameter("name")<br/>
3 $session<br/>

Velocity可以直接使用struts2的很多內建物件,比如Request、Session、Response,上面的示例演示瞭如何獲取 url請求引數

十一、include、parse實現佈局模組化

每個頁面,通常會有一些公用的頭、尾,可以用include或parse來包括其它vm檔案(或txt/html檔案),這二個的區別在於include只是簡單的把其它檔案匯入進來,不會執行任何vm語法的解析。而parse匯入其它vm檔案時,如果其它vm檔案裡有一些指令,比如定義變數,定義巨集之類,parse會解析執行。

1 #parse("template/header.vm")
2 #include("template/footer.vm")

關於載入的路徑,這裡要重點解釋一下,官方文件上也講得不清不楚,Velocity支援二種路徑載入機制,按classPath或按filePath,預設是按classPath路徑載入,即:只要被包含的.vm檔案在/WEB-INF/classes目錄下即可。上面的示例,將在/WEB-INF/classes/template目錄下,搜尋header.vm、footer.vm這二個檔案,如果找到就載入,否則出錯。

最後談下IDE以.vm的視覺化支援問題,目前最新的eclipse上,暫無好用的外掛(googlecode上的外掛大多已經沒人維護了,與最新的eclipse不相容),建議使用IntelliJ Idea,它對vm的視覺化支援程度較好。