java velocity模板用法(替换、循环、if判断)

一、.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>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值