Created
March 4, 2016 06:22
-
-
Save winteryoung/47cf878a80f6a762ed19 to your computer and use it in GitHub Desktop.
This file contains 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
import org.apache.velocity.Template; | |
import org.apache.velocity.VelocityContext; | |
import org.apache.velocity.app.VelocityEngine; | |
import java.io.StringWriter; | |
import java.util.Properties; | |
public class VelocityUtils { | |
public static String generateContent(String templatePath, | |
VelocityContext context) { | |
return generateContent(templatePath, context, VelocityUtils.class.getClassLoader()); | |
} | |
public static String generateContent(String templatePath, | |
VelocityContext context, | |
ClassLoader classLoader) { | |
ClassLoader oldClsLoader = Thread.currentThread().getContextClassLoader(); | |
Thread.currentThread().setContextClassLoader(classLoader); | |
Properties props = new Properties(); | |
props.setProperty("resource.loader", "class"); | |
props.setProperty("class.resource.loader.class", | |
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); | |
VelocityEngine ve = new VelocityEngine(props); | |
ve.init(); | |
Template tp = ve.getTemplate(templatePath, "UTF-8"); | |
StringWriter writer = new StringWriter(); | |
tp.merge(context, writer); | |
Thread.currentThread().setContextClassLoader(oldClsLoader); | |
return writer.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment