concept template in category groovy

This is an excerpt from Manning's book Groovy in Action, Second Edition.
In real life, GStrings are handy in templating scenarios. A GString is used to create the string for an SQL query. Groovy provides even more sophisticated templating support, as shown in chapter 8. If you need a dollar character within a template (or any other GString use), you must escape it with a backslash as shown in
.
The format of templates is inspired by the JSP syntax, the JSP Expression Language (EL), the Velocity framework, and GStrings. The idea is to use placeholders inside the running text. Table 12.7 lists the supported placeholders and their purpose. If you’ve ever worked with JSP or a similar technology, it will feel familiar.
Table 12.7. Template placeholders
Marker
Purpose
$variable Insert the value of the variable into the text ${groovycode} Evaluate single-line groovycode, and insert the result into the text <%=groovycode%> Evaluate the groovycode, and insert the result into the text <%groovycode%> Evaluate the groovycode The groovy.text package defines multiple template engines. These engines (the name factory would better reveal their purpose) have createTemplate methods that read the template’s raw text from an input source (String, Reader, File, or URL) and return a Template object.
Template objects can make a final text by replacing all the placeholders with their respective values. A map of variable names and their respective values (the binding) is therefore passed to the template’s make method, which returns the final text in terms of a Writable. Figure 12.3 shows how all this fits together.
Figure 12.3. Templates are created from a template engine and called with a binding to make the final result.
![]()
Different Template classes provide different runtime characteristics. One implementation might fully read the raw text and cache it for the later make step; other implementations might only store a reference to the source and merge it with the binding at make time. The latter streaming scenario can use source Readers and result Writers for optimized performance and scalability.
Groovy is a pragmatic language. Rather than following any dogma in language and library design, it focuses on getting recurring tasks done. Working with templates is such a task.
A template is essentially text. Unlike fixed literal text, a template allows predefined modifications. These modifications follow some structure; they don’t occur wildly.
If you think about a web application, literal text would be a static HTML page. At the other end of the continuum are web application frameworks that create such HTML solely by programming logic, such as JavaServer Faces (JSF). In between are approaches like JavaServer Pages (JSP) and others that create the final HTML from a template.
.