Velocity是一个基于Java的模板引擎,其提供了一个Context容器,在java代码里面我们可以往容器中存值,然后在vm文件中使用特定的语法获取,这是velocity基本的用法,其与jsp、freemarker并称为三大视图展现技术,相对于jsp而言,velocity对前后端的分离更加彻底:在vm文件中不允许出现java代码,而jsp文件中却可以.
作为一个模块引擎,除了作为前后端分离的MVC展现层,Velocity还有一些其他用途,比如源代码生成、自动email和转换xml等,具体的用法可以参考这篇文章
基础语法
<html>
<body>
<pre>
Hello VM.
## 使用$vari获取变量时,如果变量不存在,Velocity引擎会将其原样输出,通过使用\$!{}的形式可以将不存在的变量变成空白输出.
$!{value1}
$!{value2}
${value3}
## $!{foreach.count}记录当前循环次数的计数器,默认从1开始计数
#foreach($color in $colors)
Color $!{foreach.index}/$!{foreach.count}: $!{color}
#end
#foreach($key in $map.keySet())
Number $!{foreach.index}/$!{foreach.count}: $!{key} $map.get($!{key})
#end
#foreach($kv in $map.entrySet())
Number $!{foreach.index}/$!{foreach.count}: $!{kv.key} $!{kv.value}
#end
User:$!{user.name}
User:$!{user.getName()}
## 定义变量
#set($title = "coder")
## 纯文本扩展
Include: #include("header.vm") <br>
## 变量解析
Parse:#parse("header.vm")
## 在Velocity中也有宏的概念,可以将其作为函数来理解,使用#macro声明宏
#macro (render_color $color, $index)
Color By Macro $index, $color
#end
#foreach ($color in $colors)
#render_color($color, $foreach.index)
#end
#set($hello = "hello")
#set($hworld1 = "$!{hello} world")
#set($hworld2 = '$!{hello} world')
$!{colors.size()}
hworld1:$hworld1
hworld2:$hworld2
</pre>
</body>
</html>
- velocity中变量是弱类型的。
- ${name} ,也可以写成:$name。提倡用前面的写法。
- 在Velocity中可以通过parse或者include指令引入外部vm文件,但是二者存在区别:include指令会将外部文件原样输出,而parse指令会先对其进行解析再输出(即对外部文件中的vm语法解析)。
- 详细语法参见这里。