Included with Groovy are several template engines:
Output
File content
Output
SimpleTemplateEngine
- for basic templatesGStringTemplateEngine
- 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();
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();
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?: ""}
Dear Pritom Mondal, So nice to meet you in "this evening". So nice to meet you in "this morning". See you in February