工作以后,我越来越能体会到 80/20 法则的强大。
这是一个不可否认的事实,常用 20% 的技术可以解决工作中 80% 的场景。 所以我希望能介绍给你 Velocity 技术 20%,帮助你胜任 80% 的工作。
废话少说,进入正题。
Velocity 是一个基于 Java 的模版引擎,它提供模版语言用于引用 Java 代码定义的对象。
##
#* *#
##* *#
定义:
#set( $foo = "Velocity" )
使用:
$foo
${foo}
#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#if( $foo < 10 )
<strong>Go North</strong>
#elseif( $foo == 10 )
<strong>Go East</strong>
#else
<strong>Go West</strong>
#end
#foreach( $customer in $customerList )
#if( $foreach.count > 5 )
#break
#end
$customer.Name
#end
#include( "one.vm" ) one.vm 不解析。
#parse( "me.vm" ) me.vm 解析。
#define( $block )
Hello $who
#end
#set( $who = 'World!' )
$block
#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>
<!- 输出 -->
<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>
1. 各种写法
$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:
5. #if ($foo == $bar)
因为 Velocity 变量最终都作为字符串输出,所以 Velocity 会自动调用 .toString() 将变量转换成字符串。 所以,$foo 和 $bar 都当成字符串进行比较。即使 Java 代码中类型不同,也有可能返回 true。
Velocity 1.6 引入**严格引用模式**,通过设置 Velocity 配置属性“runtime.references.strict”为 true 激活。 当遇到没有定义或者存在歧义的情况 Velocity 将抛出异常。
希望这篇文章对你有帮助。