Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

Introduction

Groovy supports multiple ways to generate text dynamically including GStrings, printf if you are using Java 5, and MarkupBuilder just to name a few. In addition to these, there is a dedicated template framework which is well-suited to applications where the text to be generated follows the form of a static template.

Template framework

The template framework in Groovy consists of a TemplateEngine abstract base class that engines must implement and a Template interface that the resulting templates they generate must implement.

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

Shown here is the SimpleTemplateEngine that allows you to use JSP-like scriptlets (see example below), script, and EL expressions in your template in order to generate parameterized text. Here is an example of using the system:

Code Block
java
java
import groovy.text.SimpleTemplateEngine

def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}'

def binding = ["firstname":"Sam", "lastname":"Pullara", "city":"San Francisco", "month":"December", "signed":"Groovy-Dev"]

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

def result = 'Dear "Sam Pullara",\nSo nice to meet you in San Francisco.\nSee you in December,\nGroovy-Dev'

assert result == template.toString()

While it is generally not deemed good practice to mix processing logic in your template (or view), sometimes very simple logic can be useful. E.g. in the example above, we could change this:

Code Block
$firstname

to this (assuming we have set up a static import for capitalize inside the template):

Code Block
${capitalize(firstname)}

or this:

Code Block
<% print city %>

to this:

Code Block
<% print city == "New York" ? "The Big Apple" : city %>

Advanced Usage Note

If you happen to be embedding your template directly in your script (as we did above) you have to be careful about backslash escaping. Because the template string itself will be parsed by Groovy before it is passed to the the templating framework, you have to escape any backslashes inside GString expressions or scriptlet 'code' that are entered as part of a Groovy program. E.g. if we wanted quotes around The Big Apple above, we would use:

Code Block
<% print city == "New York" ? "\\"The Big Apple\\"" : city %>

Similarly, if we wanted a newline, we would use:

Code Block
\\n

in any GString expression or scriptlet 'code' that appears inside a Groovy script. A normal "\n" is fine within the static template text itself or if the entire template itself is in an external template file. Similarly, to represent an actual backslash in your text you would need

Code Block

in an external file or

Code Block

in any GString expression or scriptlet 'code'. (Note: the necessity to have this extra slash may go away in a future version of Groovy if we can find an easy way to support such a change.)

GStringTemplateEngine

As an example of using the GStringTemplateEngine, here is the example above done again (with a few changes to show some other options). First we will store the template in a file this time:

Code Block
titletest.template
Dear "$firstname $lastname",
So nice to meet you in <% out << (city == "New York" ? "\"The Big Apple\"" : city) %>.
See you in ${month},
${signed}

Note that we used out instead of print to support the streaming nature of GStringTemplateEngine. Because we have the template in a separate file, there is no need to escape the backslashes. Here is how we call it:

Code Block
def f = new File('test.template')
engine = new GStringTemplateEngine()
template = engine.createTemplate(f).make(binding)
println template.toString()

and here is the output:

Code Block
none
none
Dear "Sam Pullara",
So nice to meet you in "The Big Apple".
See you in December,
Groovy-Dev

You can also plug in other templating solutions, e.g. GFreeMarker, Velocity, StringTemplate, Canvas and others.

If you wish to combine templating with Ant processing, consider Gpp.

Using TemplateServlet to serve single JSP-like HTML files

Note
titleMind the gap! Ehm, meaning the difference between Groovlets and Templates.

The TemplateServlet just works the opposite as the Groovlets(GroovyServlet) does. Here, your source is HTML (or any other, fancy template files) and the template framework will generate a Groovy script on-the-fly. This script could be saved to a .groovy file and served by the GroovyServlet (and the GroovyScriptEngine), but after generation, the template is evaluated and responded to the client.

Here is a simple example helloworld.html file which is not validating and does not have a head element. But it demonstrates, how to let Groovy compile and serve your HTML files to web clients. The tag syntax close to JSP and should be easy to read:

Code Block
xml
xml
<html>
  <body>
    <% 3.times { %>
      Hello World!
    <% } %>
    <br>
    <% if (session != null) { %>
      My session id is ${session.id}
    <% } else println "No session created." %>
  </body>
</html>


The first Groovy block - a for loop - spans the HelloWorld! text. Guess what happens? And the second Groovy statement prints the servlet's session id - if there is a session avaiable. The variable session is one of some default bound keys. More details reveals the documentation of ServletBinding.

Here is some sample code using http://jetty.mortbay.orgs servlet container. With jetty6.0, dependencies added through Grape, create a tiny web server with the following. To test it, add your above helloworld.html file into your current directory and browse http://localhost:1234/helloworld.html

Code Block
@GrabResolver(name='codehaus-release-repo', root='http://repository.codehaus.org')
@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.11')

import org.mortbay.jetty.*
import org.mortbay.jetty.servlet.*
import groovy.servlet.*

def server = new Server(1234)
def root = new Context(server,"/",Context.SESSIONS)
root.setResourceBase(".")
root.addServlet(new ServletHolder(new TemplateServlet()), "*.html")
server.start()

Here is a similiar web.xml example.

Code Block
xml
xml
<web-app>

    <servlet>
      <servlet-name>Groovlet</servlet-name>
      <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Template</servlet-name>
        <servlet-class>groovy.servlet.TemplateServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Groovlet</servlet-name>
        <url-pattern>*.groovy</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Template</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Template</servlet-name>
        <url-pattern>*.gsp</url-pattern>
    </servlet-mapping>

</web-app>

Further reading

Article on templating with Groovy templates
Article on templating with Groovlets and TemplateServlets
Blog about combining Groovy and FreeMarker