velocity模板引擎学习

  velocity(vm)模板引擎学习介绍及语法   .

velocity与freemaker、jstl并称为Java web开发三大标签技术,并且velocity在codeplex上还有.net的移植版本NVelocity,(注:castle团队在github上也维护了一个版本)对于使用异构技术的团队(即要搞.NET又要搞JAVA),老是但愿找一种通用的技术,兼容全部技术平台,以便下降学习成本,无疑velocity是一种值得考虑的选择。

1、与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)三种模板。

 

2、定义变量

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二行输出内容

 

3、遍历数组

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

解释:定义了一个数组,而后遍历输出,其中velocityCount为索引变量

 

4、遍历HashTable

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


5、判断是否为空


复制代码
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

复制代码

 


6、宏示例

宏能够理解为“函数”,定义一个宏即至关于定义一个子函数,调用宏,即为调用子函数


复制代码
 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)

复制代码


7、数值、日期格式化


复制代码
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中注册便可。

 

 

8、国际化

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就能取到国际化的内容了

 

9、使用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/> 

 

10、内建对象

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

Velocity能够直接使用struts2的不少内置对象,好比Request、Session、Response,上面的示例演示了如何获取 url请求参数

 

11、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的可视化支持程度较好。
相关文章
相关标签/搜索