Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 7 Next »

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 is the SimpleTemplateEngine that allows you to use JSP-like scriptlets, script, and EL expressions in your template in order to generate parametrized text. Here is an example of using the system:

Error rendering macro 'code': Invalid value specified for parameter 'lang'
import groovy.text.Template
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()

Though its possible to plug in any kind of template engine dialect, we can share the same API to invoke templates. e.g. we could create a Velocity / FreeMarker flavour TemplateEngine implemenation which could reuse GPath and auto-recompile to bytecode.

Using TemplateServlet to serve single JSP-like HTML files

Here is a simple example helloworld.html file which is not validating and does not have an 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:

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. The variable session is one of some default bound keys. More details reveals the documentation of groovy.servlet.ServletBinding.

Here is some sample code using http://jetty.mortbay.orgs servlet container. Just get the latest Jetty jar and put this excerpt in a main method, organize the imports and start! Note, that the servlet handler also knows how to serve *.groovy files and supports dumping:

TODO Provide web.xml

The TemplateServlet just works the other way as the Groovlets#Groovlets (GroovyServlet) does. Here, your source are 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 the served by GroovyServlet (and the GroovyScriptEngine), but after generation, the template is evaluated and responded to the client.

Further reading

Article on templating with Groovy templates by Andrew Glover

  • No labels