快速依赖
<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>
使用字符串模板
// 初始化模板引擎 VelocityEngine ve = new VelocityEngine(); ve.init(); String text = "Hello, ${name}"; // 设置变量 VelocityContext ctx = new VelocityContext(); ctx.put("name", "Velocity"); // 输出 StringWriter sw = new StringWriter(); ve.evaluate(ctx, sw, "test", text); System.out.println(sw.toString());
使用模板文件
VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); ve.init(); // 获取模板文件 Template t = ve.getTemplate("template/hello.vm"); // resources下的template目录 // 设置变量 VelocityContext ctx = new VelocityContext(); ctx.put("name", "Velocity"); // 输出 StringWriter sw = new StringWriter(); t.merge(ctx, sw); System.out.println(sw.toString());
参考
https://www.jianshu.com/p/5913903324ff