一、eclipse编译器安装velocity
1、eclipse中安装插件
在help -> Eclipse Marketplace 搜索-> velocity 安装veloeclipse 3.0.1
2、maven项目pom中配置velocity-jar
<!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
二、源码案例
public static void main(String[] args) throws IOException {
VelocityEngine velocity = new VelocityEngine();
Properties properties = new Properties();
// 指定字符集
properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
String basePath = "templates";//路径为.vm文件所在的文件夹名称!!!此处文件名为templates
// 设置模板的路径
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);
// 初始化velocity 让设置的路径生效
velocity.init(properties);
// 获取模版
Template template = velocity.getTemplate("first.vm");
// 创建context
VelocityContext context = new VelocityContext();
// 添加数据
context.put("name", new String("Velocity"));
// Merge 模版和context
StringWriter writer = new StringWriter();
template.merge(context, writer);
//渲染到控制台
System.out.println(writer.toString());
writer.close();
}
此处为了演示路径问题
三、源码案例2,将vm文件渲染到HTML页面
public static void main(String[] args) throws IOException {
VelocityEngine velocity = new VelocityEngine();
Properties properties = new Properties();
// 指定字符集
properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
String basePath = "templates";// 这里需要这样写路径!!!
// 设置模板的路径
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);
// 初始花velocity 让设置的路径生效
velocity.init(properties);
// 获取模版
Template template = velocity.getTemplate("first.vm");
// 创建context
VelocityContext context = new VelocityContext();
// 添加数据
context.put("name", new String("Velocity"));
//将list集合添加到context
List<String> list = new ArrayList<String>();
list.add("方便面");
list.add("娃哈哈");
list.add("大大泡泡糖");
list.add("AD钙中钙");
context.put("list", list);
//输出到001.html文件所在路径
FileOutputStream fos = new FileOutputStream("html/001.html");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
// Merge 模版和context
template.merge(context, writer);
writer.close();
System.out.println("渲染完成!");
}
first.vm模板内容
##单行注释 #*多行注释*#
<tbody>
<tr>获取后端的值:$name</tr>
## #set用于变量赋值
<tr>set赋值</tr>
#set($a = 1)
#set($b = 2)
<tr>$a,$b</tr>
#set( $list1 = ["a","b","c"] )
<tr>$list1</tr>
## #stop停止指令,即停止模板引擎的执行,可用于程序调试,注意不用能在#if和#foreach中使用
<tr>此处停止</tr>
## #stop
## #if判断
<tr>if判断</tr>
#if($b<$a)
$b
#else
$a
#end
## #foreach循环遍历
<tr>foreach循环遍历</tr>
#foreach($i in $list)
<tr>$i</tr>
#end
## #include 指令导入本地文件,可包含多个,中间用逗号分隔
<tr>本地文件info.txt</tr>
#include("info.txt")
## #macro 宏指令,可用于定义代码段,宏内还可以带参数
##定义宏:#macro(t)
#macro(t)
<span>yes</span>
#end
<tr>使用宏</tr>
#t()
##定义带参数的宏
#macro(y $p)
<span>$p</span>
#end
<tr>使用带参数的宏</tr>
#y("yes")
</tbody>