一、eclipse编译器安装velocity
1、eclipse中安装插件
在help -> Eclipse Marketplace 搜索-> velocity 安装veloeclipse 3.0.1
2、maven项目pom中配置velocity-jar
org.apache.velocity velocity1.7
二、源码案例
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 list = new ArrayList();
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模板内容
##单行注释 #*多行注释*#获取后端的值:$name ## #set用于变量赋值set赋值 #set($a = 1) #set($b = 2)$a,$b #set( $list1 = ["a","b","c"] )$list1 ## #stop停止指令,即停止模板引擎的执行,可用于程序调试,注意不用能在#if和#foreach中使用此处停止 ## #stop ## #if判断if判断 #if($b<$a) $b #else $a #end ## #foreach循环遍历foreach循环遍历 #foreach($i in $list)$i #end ## #include 指令导入本地文件,可包含多个,中间用逗号分隔本地文件info.txt #include("info.txt") ## #macro 宏指令,可用于定义代码段,宏内还可以带参数 ##定义宏:#macro(t) #macro(t) yes #end使用宏 #t() ##定义带参数的宏 #macro(y $p) $p #end使用带参数的宏 #y("yes")



