最小的 Velocity 教程

工做之后,我愈来愈能体会到80/20法则的强大。
这是一个不能否认的事实,经常使用 20% 的技术能够解决工做中 80% 的场景。
因此我但愿能介绍给你 Velocity 技术 20%,帮助你胜任 80% 的工做。html

废话少说,进入正题。java

概要

  1. Velocity 是什么?
  2. Velocity 能作什么?
  3. Velocity 示例

1. Velocity 是什么?

Velocity 是一个基于Java的模版引擎,它提供模版语言用于引用Java代码定义的对象。code

2. Velocity 能作什么?

  1. Velocity能建立HTML页面,并预留占位符。(最基本用途)
  2. Velocity能基于模板生成Java,SQL源代码。(没见过)
  3. 自动生成电子邮件。(没见过)
  4. 读取XML,并转换成须要的文档格式,一般是HTML。(没见过)

3. Velocity示例

Velocity 注解

单行 ##
多行 #* *#
代码块注释(信息) ##* *#htm

Velocity 变量

定义:对象

#set( $foo = "Velocity" )

使用:ci

$foo
${foo}

Velocity 集合

#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )

Velocity 条件判断

#if( $foo < 10 )
    <strong>Go North</strong>
#elseif( $foo == 10 )
    <strong>Go East</strong>
#else
    <strong>Go West</strong>
#end

Velocity 循环

#foreach( $customer in $customerList )
    #if( $foreach.count > 5 )
        #break
    #end
    $customer.Name
#end

Velocity 引用文件

#include( "one.vm" ) one.vm 不解析。
#parse( "me.vm" ) me.vm 解析。

Velocity 定义代码块

#define( $block )
Hello $who
#end

#set( $who = 'World!' )
$block

Velocity 宏调用

  • 无参
#macro( d )
<tr><td></td></tr>
#end

#d()
  • 单参
#macro( d )
<tr><td>$!bodyContent</td></tr>
#end

#@d()Hello#end
  • 任意参数

定义文档

#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>

输出get

<table>
    <tr><td bgcolor="blue">Superior</td></tr>
    <tr><td bgcolor="blue">Michigan</td></tr>
    <tr><td bgcolor="blue">Huron</td></tr>
    <tr><td bgcolor="blue">Erie</td></tr>
    <tr><td bgcolor="blue">Ontario</td></tr>
</table>

Velocity 填坑

1. 各类写法it

$foo
## is the same as
${foo}

$foo.getBar()
## is the same as
$foo.Bar

$data.setUser("jon")
## is the same as
#set( $data.User = "jon" )

$data.getRequest().getServerName()
## is the same as
$data.Request.ServerName
## is the same as
${data.Request.ServerName}

2. Velocity 变量未定义
使用 $!,例

$!foo

当 foo 未定义,输出空白字符串。

3. Velocity 调用顺序
Velocity中$customer.address,调用顺序:

getaddress()
getAddress()
get("address")
isAddress()

4. #if ($foo)
两种状况都返回true:
(1)$foo是一个 boolean 类型,且为 true。
(2)$foo不是 0,也不是 null。

5. #if ($foo == $bar)
由于Velocity变量最终都做为字符串输出,因此Velocity会自动调用 .toString() 将变量转换成字符串。
因此,$foo 和 $bar 都当成字符串进行比较。即便Java代码中类型不一样,也有可能返回true。

Velocity 严格模式

Velocity 1.6引入严格引用模式,经过设置Velocity配置属性“runtime.references.strict”为true激活。
当遇到没有定义或者存在歧义的状况Velocity将抛出异常。

但愿这篇文章对你有帮助。by iamtjcn

相关文章
相关标签/搜索