Groovy now has a template framework


Groovy now has a template framework

Cedric pointed out that Groovy would be a great language to use to make templates along with a simple JSP-like syntax. Since I had thought about this before, I decided that it would be a good addition to the core of Groovy.

After talking it over with the rest of the Groovy crew we settled on making a template framework that includes an abstract base class for template engines and an interface that represents a template. The template engine can construct templates from a text source and the template can then be bound to a set of variables. Templates are evaluated by either using toString() or through the Writable interface for efficiency. I went one step further and made a SimpleTemplateEngine that includes the <% statements %>, <%= expression %>, and ${expresssion} syntax from JSP 2.0 along with an implicit Writer named “result”. Well worth its 150 lines of code. It takes your template, replaces the markup with our version of heredocs, and compiles the result into a Groovy script that can be executed again and again with different bindings. Since Canvas was targetted at Java users, I’ll give an 
example of usage from Java (please excuse my exception non-handling):

import java.io.*; import java.util.*; import groovy.lang.*; import groovy.text.*;  public class TemplateTest {     public static void main(String[] args) throws Exception {         Properties p = new Properties();         p.load(new FileInputStream(args[1]));         Template template = new SimpleTemplateEngine().createTemplate(new FileReader(args[0]));         template.setBinding(p);         System.out.println(template);     } }

Then you can have a couple of files, a template:

test.template:

Dear ${firstname} ${lastname},  So nice to meet you in ${city}.  See you in ${month}, ${signed}, ${new java.util.Date()}

test.properties:

firstname=Sam lastname=Pullara city=San Francisco month=December signed=Groovy-Dev

Then run this little gem with groovy/asm in the classpath:

/Users/sam:> java TemplateTest test.template test.properties   Dear Sam Pullara,  So nice to meet you in San Francisco.  See you in December, Groovy-Dev, Mon Mar 08 20:23:56 PST 2004