velocity三种reference
变量:对java对象的一种字符串化表示,返回值调用了java的toString()方法的结果。
方法:调用的是对象的某个方法,该方法必须是public的,返回值也是toString(),方法的参数也必须为String的。
属性:除了访问java的类属性外,等价于get..()方法。
基本符号
1、“#”来标识velocity的脚本语句。包括#set、#if 、#else、#end、#foreach、#end、#iinclude、#parse、#macro等;
2、“$”来标识一个对象(或者变量)。
3、“{}”用来标识velocity变量。
4、“!”用来强制把不存在的变量显示为空白。
5、用双引号还是单引号表示,默认“”,可以在stringliterals.interpolate=false改变默认处理方式
1、变量
velocity变量是弱类型的,使用$声明变量,使用#set对变量赋值,另外可以使用$取出VelocityContext容器中存放的值。
#set(${!name} = "velocity")
#set(${!foo} = $bar)
#set($foo = "hello")
#set($foo.name = $bar.name)
#set($foo.name = $bar.getName($arg))
#set($foo = 123)
#set($foo = ["foo", $bar])
#($name="hello")
#($templateName = "index.vm")
#set($template = "$directoryRoot/$templateName")
#template
注意上面代码中$!{}的写法,使用$variable获取变量时,如果变量不存在,velocity引擎会将其原样输出,通过使用$!{}的形式可以将不存在的变量变成空白输出。
2、分支
#if(condition)
...dosonmething...
#elseif(condition)
...dosomething...
#else
...dosomething...
#end
#if(condition)
#elseif(condition)
#else
#end
例如
#set($arr=["jiayou","jiayou2","jiayou3"])
#foreach($element in $arr )
#if($velocityCount==1)
<div>jiayou</div>
#elseif($velocityCount==2)
<div>jiayou2</div>
#else
<div>jiayou3</div>
#end
#end
3、循环
#foreach($element in $list)
This is $element
$velocityCount
#end
例如:
#set($list=["pine","oak","maple"])
#foreach($element in $list)
$velocityCount
This is $element.<br>
#end
输出结果为:
this is pine
this is oak
this is maple
$list 可以为Vector、Hashtable、Array。分配给$element 的值是一个java对象,并且可以通过变量被引用。
例如
#foreach($key in $list.keySet)
Key: $key--->value: $list.get($key) <br>
#end
Velocity 还提供了循环次数的方法,$velocityCouont变量的名字是Velocity默认的名字,表示循环到第几次了。
#foreach($item in $list)
$item
$velocityCount
#end
$item代表遍历的每一项,$velocityCount是velocity提供的用来记录当前循环次数的计数器,默认从1开始计数,可以在velocity.properties文件中修改其初始值。
4、宏
在velocity中也有宏的概念,可以将其作为函数来理解,使用#macro声明宏。
## 声明宏
#macro(sayHello $name)
hello $name
#end
## 使用宏
#sayHello("NICK")
5、parse和include指令
在velocity中可以通过parse或者include指令引入外部vm文件,但是二者存在区别:include指令会将外部文件原样输出,而parse指令会先对其进行解析再输出(即对外部文件中的vm语法解析)。
#include和#parse的作用都是引入本地文件,为了安全,被进入的文件只能在Template_root目录下。
这两个引入区别:
1)#include可以引入多个文件。例如:#include(“one.gif”,”two.txt”,”three.html”)
#parse只能引入指定的单个对象。例如:#parse(“layout/index.vm”)
2)#include引入的文件内容不会被velocity模板引擎解析。
#parse引入的文件内容,将解析其中的velocity并交给模板,相当于把引入的文件内容copy到文件中。
3)#parse是可以递归调用的。
#parse("header.vm")
#include("footer.vm")
6、注释
单行注释:##this is single
多行注释:#* ………#
文档格式:#………….#
7、关系和逻辑操作符
&& == || !
#if($foo && $bar)
<strong> This AND that</strong>
#end