Description
Velocity Apache adalah template engine yang berguna untuk meng inject file atau data seperti XML, HTML, SQL, dll
Maven
<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>
Java Class
public interface TemplateEngine {
String generate(String template, Map<String, Object> params);
}
public class VelocityTemplateEngine implements TemplateEngine{
@Override
public String generate(String template, Map<String, Object> params) {
try {
if(params == null) params = new HashMap<>();
RuntimeServices velocityService = RuntimeSingleton.getRuntimeServices();
Template velocityTemplate = new Template();
velocityTemplate.setData(velocityService.parse(new StringReader(template), String.valueOf(velocityTemplate)));
velocityTemplate.setRuntimeServices(velocityService);
VelocityContext velocityContext = new VelocityContext();
params.forEach(velocityContext::put);
StringWriter writer = new StringWriter();
velocityTemplate.initDocument();
velocityTemplate.merge(velocityContext, writer);
String result = writer.toString();
writer.close();
writer.flush();
return result;
} catch (ParseException | IOException e) {
throw new IllegalStateException();
}
}
}
How To Use
public class Main {
public static void main(String[] args) {
TemplateEngine templateEngine = new VelocityTemplateEngine();
String template = "Hallo, $name ! $say";
Map<String, Object> map = new HashMap<>();
map.put("name", "Petrik");
map.put("say", "Apa Kabar?");
System.out.println(templateEngine.generate(template, map));
}
}
Komentar
Posting Komentar