一、添加依赖包
compile group: 'org.apache.velocity', name: 'velocity', version: '1.7'
二、创建模板文件
在resources目录下,新建文件夹vm,新建文件vm文件,命名:HelloVelocity.vm
#set( $iAmVariable = "good!" )
Welcome $name to velocity.com
today is $date.
#foreach ($i in $list)
$i
#end
$iAmVariable
三、编写测试方法
注:读取vm模版时,路径和文件名(包括大小写)要对应上
Template t = ve.getTemplate("vm/HelloVelocity.vm");
public String testVelocityEngine() {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
// 载入(获取)模板对象
Template t = ve.getTemplate("vm/HelloVelocity.vm");
VelocityContext ctx = new VelocityContext();
// 域对象加入参数值
ctx.put("name", "best");
ctx.put("date", (new Date()).toString());
// list集合
List list = new ArrayList();
list.add("1111");list.add("2222");
list.add("3333");list.add("4444");
ctx.put("list", list);
StringWriter sw = new StringWriter();
t.merge(ctx, sw);
System.out.println(sw.toString());
return "testVelocityEngine";
}
运行结果:
Welcome best to velocity.com
today is Fri Dec 21 15:47:22 CST 2018.
1111
2222
3333
4444
good!
四、模版语法
1、定义变量
#set($name =“Best”)
#set($hello =“hello $name”)
Best赋值给$name
,此时$hello
的值为hello Best
2、循环
#foreach($element in $list)
This is $element
$velocityCount
#end
3、条件语句
#if(condition)
...
#elseif(condition)
…
#else
…
#end
ex:
#set ($admin = "admin")
#set ($user = "user")
#if ($admin = = $user)
Welcome admin!
#else
Welcome user!
#end
4、自定义函数
#macro(macroName arg1 arg2 …)
...
#end
// 对应函数
#macroName(arg1 arg2 …)
5、