Velocity使用示例
Velocity使用步骤
- 引入依赖
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
- 编写启动类,以测试类为例。
package org.dsg.velocity;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import java.io.FileWriter;
import java.util.Properties;
public class VelocityTest {
@Test
public void testQuickStart() throws Exception{
Properties props = new Properties();
props.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(props);
VelocityContext context = new VelocityContext();
context.put("name", "Robert");
Template template = Velocity.getTemplate("vms/quickstart.vm", "UTF-8");
FileWriter writer = new FileWriter("C:\\quickstart.html");
template.merge(context, writer);
writer.close();
}
}
- 编写模板文件vms/quickstart.vm;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
## 单行注释
#*
* 多行注释
*#
#**
*
* 属性引用
* $变量名.属性 如果没有对应变量,则原样直接输出
* $!变量名.属性 如果没有对应的变量,输出空串
*
**#
Hello, ${name}!
<h1>非解析内容</h1>
#[[
非解析内容
${name}
]]
<h1>引用属性</h1>
常规语法: $!{user.name}
<h1>指令</h1>
## #set用来声明数据,可以引用之前定义过的变量
#set($str="Hello World")
#set($int=10)
#set($arr=[1, 2, 3, 4])
#set($boolean=true)
#set($map={"key":"value"})
#set($str2 = "Hello, how are you, $str !")
## 获取声明的变量
字符串:$str ${str2}
整型:$int
数组:$arr
布尔:$boolean
Map.key: $map.key
## 条件查询
#set($language="java")
#if($language.equals("java"))
JAVA开发工程师
#elseif($language.equals("php"))
PHP工程师
#else
工程师
#end
## 遍历循环数组或集合
#set($hobbies=["eat", "drink", "play", "music"])
#foreach($hobby in $hobbies)
$foreach.index -- $foreach.count -- $hobby
#end
#* #include引入外部资源,不会被引擎所解析
* #parse(resource) 引入外部的资源,资源将被引擎所解析,如果配置的是相对路径,是以引擎配置的文件加载器加载路径作为参考系
* #define($模块名称) 定义不带参数的重用模块
* #evaluate("计算语句") 动态计算,可以让我们在字符串中使用变量
* #macro(宏名称 参数) 定义可带参数的重用模块
*#
<h1>定义模块</h1>
#define($hello)
Hello ${who}!
#end
#set($who="World")
调用模块:
$hello
#macro(table $users)
<table border="1px" align="center">
<tr>
<td>编号</td>
<td>用户名</td>
<td>密码</td>
</tr>
#foreach($user in $users)
<tr>
<td>$foreach.count</td>
<td>$user.username</td>
<td>$user.password</td>
</tr>
#end
</table>
#end
#set($users=[{"username":"张三", "password":"123"}, {"username":"李四", "password":"456"}])
#table($users)
</body>
</html>
- 运行测试类,在指定路径下得到了quickstart.html。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello, Robert!
<h1>非解析内容</h1>
非解析内容
${name}
<h1>引用属性</h1>
常规语法:
<h1>指令</h1>
字符串:Hello World Hello, how are you, Hello World !
整型:10
数组:[1, 2, 3, 4]
布尔:true
Map.key: value
JAVA开发工程师
0 -- 1 -- eat
1 -- 2 -- drink
2 -- 3 -- play
3 -- 4 -- music
<h1>定义模块</h1>
调用模块:
Hello World!
<table border="1px" align="center">
<tr>
<td>编号</td>
<td>用户名</td>
<td>密码</td>
</tr>
<tr>
<td>1</td>
<td>张三</td>
<td>123</td>
</tr>
<tr>
<td>2</td>
<td>李四</td>
<td>456</td>
</tr>
</table>
</body>
</html>