August 27, 2009

Grassroots Groovy: the Templating Route

We can introduce Groovy into our projects at grassroots level. If we need some templating functionality in our Java application we can use Groovy templates. Groovy templates allow us to write Groovy code, use JSP expressions or use variables in the template. Basically a template contains static text with placeholders and we combine the template with 'live' objects through binding. The result is a the template with all placeholders replaced with the correct values from the binding and expressions.

Let's start with a template named mail.gtpl:

Hello $person.firstname $person.lastname,

Thank you registering with our company at ${ new Date().format('MMM dd, yyyy') }.

Your username is <%= person.username %>.
You have signed up for the following <% out << (person.topics.size() == 1) ? ' topic' : person.topics.size() + ' topics' %>:
<% person.topics.each { %>
- $it
<% } %>


Because this is an example we use all possible ways to express values and Groovy code. We use the <% %>, <%= %>, $var and ${expression} syntax. At line 7 we use the out variable, which is bound to a Writer object. Now we write the Java code that can use and execute this Groovy template:

package com.mrhaki.blog;

import java.io.*;
import java.util.*;
import groovy.text.*;
import groovy.lang.*;

public class TemplateApp {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Initialize template.
        final TemplateEngine engine = new GStringTemplateEngine();
        final Template template = engine.createTemplate(new File("mail.gtpl"));
        // Create Map for binding objects to template.
        final Map<String, Object> binding = new HashMap<String, Object>();
        binding.add("greeting", "Kind regards,\n\nThe Company");
        binding.add("person", new PersonObject());
        // Bind Map to template.
        final Writeable out = template.make(binding);
        // We use a Writer object, can be any Writer e.g. FileWriter.
        final StringWriter writer = new StringWriter();

class PersonObject {
    public String getFirstname() { 
        return "Hubert"; 
    public String getLastname() { 
        return "Klein Ikkink"; 
    public String getUsername() { 
        return "mrhaki"; 
    public List<String> getTopics() { 
        return Arrays.asList(new String[] { "Groovy", "Grails", "Java" }); 

When we run the Java application (make sure the Groovy libraries are in the Java classpath) we get the following output:

Hello Hubert Klein Ikkink,

Thank you registering with our company at Aug 26, 2009.

Your username is mrhaki.
You have signed up for the following 3 topics:
- Groovy
- Grails
- Java

Kind regards,

The Company

In this post we learned another way to introduce Groovy in Java projects: templates. Groovy templates are flexible and allow the use of Groovy code in the template. Integration with Java is simple and easy.