Wednesday, February 19, 2014

Groovy template engine

Included with Groovy are several template engines:
  • SimpleTemplateEngine - for basic templates
  • GStringTemplateEngine - stores the template as writable closures (useful for streaming scenarios)
  • XmlTemplateEngine - works well when the template and output are valid XML

SimpleTemplateEngine


import groovy.text.SimpleTemplateEngine

def text = 'Dear ${contact.firstName} ${contact.lastName}${contact.nickName? " " + contact.nickName: ""}.\n${time} is good.'

def binding = ["time":"this evening", month: "February", "contact": ["firstName": "Pritom", "lastName": "Mondal", age: 27]]

def engine = new SimpleTemplateEngine()

def template = engine.createTemplate(text).make(binding)

println template.toString();
Output
Dear Pritom Mondal.
this evening is good.

GStringTemplateEngine


import groovy.text.GStringTemplateEngine

File templateFile = new File("web-app/test.txt");
def templateEngine = new GStringTemplateEngine();
def templateObject = templateEngine.createTemplate(templateFile).make(binding);
println templateObject.toString();
File content
Dear ${contact.firstName} ${contact.lastName},
So nice to meet you in <% out << (time == "this evening" ? "\"${time}\"" : "\"this morning\"") %>.
So nice to meet you in <% out << (time == "this evening" ? "\"this morning\"" : time) %>.
See you in ${month?: ""}
Output
Dear Pritom Mondal,
So nice to meet you in "this evening".
So nice to meet you in "this morning".
See you in February

No comments:

Post a Comment