• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Templates in Groovy

April 6, 2008 //  by Krishna Srinivasan//  Leave a Comment

1) Introduction

In this article, we will expose the various APIs for processing Templates in Groovy. A template can be thought of some static content along with some well-defined place-holders. These templates can be re-used any number of times by simply copying it and substituting the place-holders with some appropriate values. The first section of the article concentrates on the various types of Template Engines available in Groovy. And the later section of the article guides you in using the Template API. This is not an introductory article about Groovy, so novice readers can read the introductory article Introductory Article on Groovy before continuing with this article.

also read:

  • Groovy Tutorials
  • Creating JSON using Groovy
  • Developing Groovy based web application and deploying to Google App Engine

2) Groovy Template API

2.1) Templates
As mentioned earlier, generally a template is a static content with well-defined placeholders. For example, consider the following,
‘[0] and [1] went up the hill’
The above content is an example of templated content which is having two place-holders pointed by [0] and [1]. Now this templated content can be re-used any number of times as following by substituting appropriate values,
‘Jack and Jill went up the hill’
‘Mary and Rosy went up the hill’

.
.
.

‘Somebody and Nobody went up the hill’

2.2) API Support

The necessary support for programming Groovy templates is available in the groovy.text package. This package can be logically broken into three pieces as follows,

  1. Representation of a template
  2. Template Engines

We will discuss in detail in the forth coming sections.

2.2.1) Representation of a template

Template in Groovy is represented by the interface groovy.text.Template. A template usually represents some text content and they are often associated with a set of bindings. The set of bindings contains the values for the template text containing place-holders.
Values can be passed to the template text by calling the Template.make(Map bindings) method.

2.2.2) Template Engines

Template Engines are Factory classes which are used to create Template objects from a variety of sources. The source can be as simple as an ordinary text, from a file or a reader or from an URL. For example, the following code snippet creates a Template object whose content will come from a file,

File fileContainingTemplate = new File("template.txt");
TemplateEngine templateEngine = new SimpleTemplateEngine();
Template templateObject = templateEngine.createTemplate(fileContainingTemplate);

3) Code Samples

3.1) Simple Substitution

We will see how to make use of Groovy Template API for text manipulation. To start with, we will consider a simple example in the following code,
ValueInsertion.groovy

import groovy.text.*

def day = ['day' : 'Holiday']
def message = "Today is ${day} ";

def templateEngine = new SimpleTemplateEngine()
def template = templateEngine.createTemplate(message)

Writable object = template.make(day)
println object

The above code declares a map object called day which has one entry (key and value). The key is 'day' and the value for the key 'day' is Holiday. Next the program creates a template like string object called 'message' whose value is 'Today is ${day}'. Note that this templated message has a single place-holder which is denoted by ${day}. We want this place-holder to replace with the value 'Holiday' whose value is taken from the map 'day'.
The next section of the code creates the Simple Template Engine for creating templates. Next, the template object is created for the message by calling the method, TemplateEngine.createTemplate(message). Note that till now a string object is made to look like a template object with place-holders. For passing values to the templated text, we have to call the method Template.make() by passing in a map of values as shown below,

Writable object = template.make(day)

The return type of this method is a Writable object which will contain the substituted text. In our example, the binding expression in the template text as represented by ${day} and the key that we pass for making the template ['day' : 'Holiday'] should be one and the same.
The output for the above code is,

Today is ["day":"Holiday"]

3.2) JSP Syntax based Substitution

Another most common way of using place-holders is to use the JSP-based syntax for coding scriplets. For example, consider the following code,
SimpleTemplateText1.groovy

import groovy.text.*

def templateMessage =
"Web site:" + "";

def values = ['webSite' : 'www.javabeat.net',
]

SimpleTemplateEngine templateEngine = new SimpleTemplateEngine ()
def template = templateEngine.createTemplate(templateMessage)

Writable writable = template.make(values)
println writable.toString()

In the above example, <%= expression %> has been used instead of ${object}. The rest of the code remains the same. However there are minor differences between these two expressions. In the former, the expression is evaluated and the value is inserted whereas in the latter case, the value of the object is directly inserted.
The output for the above code will be as follows,

Web site:www.javabeat.net

3.3) Evaluating Groovy Code

In the above examples, we have seen that the Groovy Expression will be evaluated and the result will be inserted directly into the embedding text. Now, let us see how to evaluate Groovy expressions alone. Consider the example,
SimpleTemplateText2.groovy

import groovy.text.Template
import groovy.text.SimpleTemplateEngine

def text = 'Weather is  here at '
def binding = [
                "temperature" : "very cold",
                "location"    : "Bangalore"
                ]

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

println template

In the above case, the object text has scripts in the following format '<% ... %>'. In such cases, the expression alone will be evaluated and the result wont be appended into the surrounding text. Here is the output of the above program,

Weather is very cold here at Bangalore

3.4) Reading text from file

ReadTemplateTextFromFile.groovy

import groovy.text.*
import java.io.*

def templateFile = new File(".\\src\\mydata.template")
def data = [
                'name' : 'Raja',
                'designation' : 'Software Engineer',
                'location' : 'Bangalore',
                ]

def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(templateFile)
def writable = template.make(data)

println writable

Till now, we have seen that the Groovy template text is hard-coded directly into the source files. Now, let us see how to externalize the template text by keeping it in a file called 'mydata.template'. The content of the file is as follows,
mydata.template

mydata.tempalte

    ${name}
    ${designation}
    ${location}

The above XML file has three place-holders for name, designation and location. Back to the source code, we have defined a map of values for these three identifiers like,

def data = [
    'name' : 'Raja',
    'designation' : 'Software Engineer',
    'location' : 'Bangalore',
]

The file object is represented by the object 'templateFile' which is shown below,

def templateFile = new File(".\\src\\mydata.template")

And this file object is passed to the template engine for reading the text content as follows,

def template = engine.createTemplate(templateFile)

3.5) GString Template Engine

GStringTemplateText1.groovy

import groovy.text.*

def templateText =
    "Call me after \n" +
    "We will meet on ";

def valuesForTemplate = [
    'time' : '6.00 OM',
    'day'  : 'Sunday evening'
]

GStringTemplateEngine templateEngine = new GStringTemplateEngine()
def template = templateEngine.createTemplate(templateText)

Writable writable = template.make(valuesForTemplate)
println writable.toString()

Various Template Engines are available in Groovy for template processing namely SimpleTemplateEngine, XmlTemplateEngine and GStringTemplateEngine. Till now, we have been using SimpleTemplateEngine for simple cases and if we want to go for template processing with performance in mind, then GStringTemplateEngine will be a better choice. XmlTemplateEngine takes care of reading the template text and writing the substituted text from and back to the XML file for fine tuning purposes and it takes care of formatting also.

4) Conclusion

In this article, we have covered the Groovy Template API. The Template API is very short and simple and it can be used widely for text processing and substitution. In the beginning of this article, we happened to see about Templates along with examples. Following that, we have explored the Template API, along with classes and interfaces with Groovy. To get a feel over the API, this various samples have been provided in the later end of the article.
The following are some of the popular articles published in Javabeat. Also you can refer the list of groovy articles and groovy books from our website. Please read the articles and post your feedback about the quality of the content.

  • Creating JSON using Groovy
  • Introduction to Groovy Server Pages (GSP)
  • Introduction to groovy

If you are interested in receiving the future java articles from us, please subscribe here.

Category: GroovyTag: Groovy, Templates in Groovy

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Previous Post: « Closures in Groovy
Next Post: AJAX – Conversation with an Ajaxian »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact