Jul 07 2008
Groovy Simple Templates
Dynamic text templates are joy to do in groovy.
I came across the need of such functionality many times during my past projects, and now with the new one.
Not only can I place my bound variables and reuse them in the template, but I can also run legal groovy code.
text = ''' Dear "$firstname $lastname", So nice to meet you in <% print city %>. See you in ${month}, ${signed} ${10.times{println it}} ''' params = [firstname:"Ali", lastname:"Baba",city:"Baghdad", month:"June", signed:"Cool-guy"] template = new groovy.text.SimpleTemplateEngine().createTemplate(text).make(params)
For this particular here-document example, note the single-quotes on the text variable, as double-quotes will cause the string to be treated as GString and hence resolve our bound variables earlier than needed.
Another way to do even simpler templates :
messageTemplate = ' "Let today ${new Date()} be a new start" ' message = evaluate(messageTemplate)
Bear in mind that the examples above are ment to cover the case where the template string comes from else where (text file, user input) and has to be processed. otherwise the evaluate example would sound useless, because one can just run the line “Let today ${new Date()} be a new start” without evaluate.