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.
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,
- Representation of a template
- 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);
|