Created
January 10, 2017 09:16
-
-
Save qiaohhgz/51604302a28f8c16d48f00c7e1dc56a5 to your computer and use it in GitHub Desktop.
velocity string template merge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.jim.util; | |
import org.apache.velocity.VelocityContext; | |
import org.apache.velocity.app.VelocityEngine; | |
import java.io.StringWriter; | |
import java.util.Map; | |
/** | |
* Created by qiaosj on 2017/1/10. | |
*/ | |
public class TemplateUtils { | |
private static VelocityEngine ve = null; | |
public static String merge(String template, Map<String, Object> map) { | |
if (template == null) return null; | |
if (map == null || map.isEmpty()) return null; | |
if (ve == null) { | |
// 初始化并取得Velocity引擎 | |
ve = new VelocityEngine(); | |
ve.init(); | |
} | |
// 取得velocity的上下文context | |
VelocityContext vc = new VelocityContext(); | |
for (String key : map.keySet()) { | |
Object val = map.get(key); | |
vc.put(key, val); | |
} | |
// 输出流 | |
StringWriter writer = new StringWriter(); | |
ve.evaluate(vc, writer, "", template); // 关键方法 | |
return writer.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment