您的位置:首页 > 其它

velocity模板引擎学习(1)

2018-03-26 16:36 232 查看
本文来自博客园--菩提树下的杨过
velocityfreemaker、jstl并称为java web开发三大标签技术,而且velocity在codeplex上还有.net的移植版本NVelocity,(注:castle团队在github上也维护了一个版本)对于使用异构技术的团队(即要搞.NET又要搞JAVA),总是希望找一种通用的技术,兼容所有技术平台,以便降低学习成本,无疑velocity是一种值得考虑的选择。
一、与strtus2的集成
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>pom.xml中加入这二项即可,其它不用刻意配置。struts2同时支持jstl(.jsp)、velocity(.vm)、freemaker(.ftl)三种模板。
二、定义变量
#set($awbpre='112')
#set($awbno='89089011')
#set($airwayBillNo=$awbpre+' - '+$awbno)
$awbpre - $awbno <br/>
$airwayBillNovelocity的语法符号大概分二类,一类用#开头,代表控制符号,#set表示定义变量,另一类用$开头,通常用于显示变量,上面的示例定义了三个变量:
awbpre 值为'112',awbno值为'89089011',airwayBillNo值为 '112 - 89089011'第4,5二行输出内容
三、遍历数组#set($list = ["CTU", "SHA", "LAX"])
#foreach ($item in $list)
$velocityCount . $item <br/>
#end解释:定义了一个数组,然后遍历输出,其中velocityCount为索引变量
四、遍历HashTable
#foreach($key in $table.keySet())
$key -> $table.get($key)<br/>
#end五、判断是否为空#if($null.isNull($orderList.orders) || $orderList.orders.size()==0)
订单列表为空
#else
订单列表:<br/>
#foreach ($order in $orderList.orders)
$velocityCount: $order.id / $order.clientName / $order.amount / $order.createTime<br/>
#end
#end上面是判断集合是否为空的,如果判断单个对象是否为空,参考下面这样:#if($(orderDto))
订单对象有值
#else
订单对象为空
#end

#if(!$(orderDto))
订单对象为空
#else
订单对象有值
#end六、宏示例
宏可以理解为“函数”,定义一个宏即相当于定义一个子函数,调用宏,即为调用子函数
#macro(renderOrderList $orders)
<table border="1">
<tr>
<th>Id</th>
<th>ClientName</th>
<th>Amount</th>
<th>CreateTime</th>
</tr>
#foreach($o in $orders)
<tr>
<td>$o.id</td>
<td>$o.clientName</td>
<td>$o.amount</td>
<td>$o.createTime</td>
</tr>
#end
</table>
#end

#renderOrderList($orderList.orders)七、数值、日期格式化$order.createTime<br/>
$date.year - $date.month - $date.day <br/>
$date.format('yyyy-MM-dd HH:mm:ss',$order.createTime,$locale)<br/>
$date.format('MMMdd',$order.createTime,$locale)<br/>
$convert.toLocale("en_US") <br/>
$date.format('MMM,dd',$order.createTime,$convert.toLocale("en_US"))<br/>
$date.format('yyyy-MM-dd',$order.createTime,$locale)<br/>
$order.amount<br/>
$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中,参考下面的内容:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<toolbox>
<tool>
<key>number</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.NumberTool</class>
</tool>
<tool>
<key>date</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.DateTool</class>
</tool>
<tool>
<key>text</key>
<scope>request</scope>
<class>org.apache.velocity.tools.struts.MessageTool</class>
</tool>
<tool>
<key>convert</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.ConversionTool</class>
</tool>
</toolbox>这些XXXTool其实是一个很好的例子,因为velocity的vm文件里不能直接写java代码,如果我们想扩展一些常用方法,可以将一些常用方法写成XXXTool工具类,然后在toolbox中注册即可。
八、国际化
当前语言环境:$locale <br/>
#stext("name=%{getText('appName')}")虽然Velocity-Tools 2.0中提供了MessageTool,但是我一直没尝试成功,只能借助struts2本身的标签来处理了。struts2中首先得定义国际化资源文件的BaseName<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”开头就行了,参考下面的示例:
#stextarea ("label=Biography" "name=bio" "cols=20" "rows=3") <br/>
#sselect("label=Favourite Color" "list={'Red', 'Blue', 'Green'}" "name=favouriteColor" "emptyOption=true" "headerKey=None" "headerValue=None")<br/> 十、内建对象$request<br/>
name = $request.getParameter("name")<br/>
$session<br/>Velocity可以直接使用struts2的很多内置对象,比如Request、Session、Response,上面的示例演示了如何获取 url请求参数
十一、include、parse实现布局模块化

每个页面,通常会有一些公用的头、尾,可以用include或parse来包括其它vm文件(或txt/html文件),这二个的区别在于include只是简单的把其它文件导入进来,不会执行任何vm语法的解析。而parse导入其它vm文件时,如果其它vm文件里有一些指令,比如定义变量,定义宏之类,parse会解析执行。
#parse("template/header.vm")
#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的可视化支持程度较好。
更详细的用法,请参考下面官司文档:
Velocity Engine 用户指南

Velocity Engine 开发人员指南

Velocity Tools 用法概述
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Velocity模板 vm