一、.vm模板文件,例如一个名为test.vm的模板文件

${name}
#foreach($nameObj in $inputNewNames)
    alert($nameObj);
#end
var obj = {//对象加逗号,用$velocityCount判断是否是最后一个
#foreach($nameObj in $inputNewNames)
    "$nameObj":$nameObj#if($velocityCount!=$inputMainNames.size()),#end
#end
}
#if($name=="111")
    alert("111");
#elseif($name=="222")
    alert("222");
#else
    alert("333");
#end

注:${name}和$name效果一样,循环里可以用$velocityCount判断,$velocityCount值默认为1

二、java文件

VelocityContext context = new VelocityContext();
context.put("name", "111");//替换文本
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
context.put("arr", list);//循环
VelocityEngine ve = new VelocityEngine();
Properties properties = new Properties();
String templatePath = FileGenerate.class.getResource("/template").getPath();//模板所在路径
properties.setProperty(ve.FILE_RESOURCE_LOADER_PATH, templatePath); //此处的fileDir可以直接用绝对路径来
ve.init(properties); //初始化
Template tpl = ve.getTemplate("test.vm", "UTF-8");
String outPath = "C:\\Users\\dell\\Desktop\\aa";//输出路径
try {
    StringWriter sw = new StringWriter();
    tpl.merge(context, sw);
    File file = new File(outPath);
    file.mkdirs();
    BufferedWriter fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPath + ".js"), "UTF-8"));//解决乱码
    PrintWriter pw = new PrintWriter(fw);
    pw.println(sw.toString());
    pw.flush();
    pw.close();
}catch (IOException e) {
    e.printStackTrace();
}

三、需要用到的包

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-tools</artifactId>
    <version>2.0</version>
</dependency>

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐