Skip to content
Skip to breadcrumbs
Skip to header menu
Skip to action menu
Skip to quick search
Quick Search
Browse
Pages
Blog
Labels
Attachments
Mail
Advanced
What’s New
Space Directory
Feed Builder
Keyboard Shortcuts
Confluence Gadgets
Log In
Sign Up
Dashboard
Groovy
Copy Page
You are not logged in. Any changes you make will be marked as
anonymous
. You may want to
Log In
if you already have an account. You can also
Sign Up
for a new account.
This page is being edited by
.
Paragraph
Paragraph
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Preformatted
Quote
Bold
Italic
Underline
More colours
Strikethrough
Subscript
Superscript
Monospace
Clear Formatting
Bullet list
Numbered list
Outdent
Indent
Align left
Align center
Align right
Link
Table
Insert
Insert Content
Image
Link
Attachment
Symbol
Emoticon
Wiki Markup
Horizontal rule
tinymce.confluence.insert_menu.macro_desc
Info
JIRA Issue
Status
Gallery
Tasklist
Table of Contents
Other Macros
Page Layout
No Layout
Two column (simple)
Two column (simple, left sidebar)
Two column (simple, right sidebar)
Three column (simple)
Two column
Two column (left sidebar)
Two column (right sidebar)
Three column
Three column (left and right sidebars)
Undo
Redo
Find/Replace
Keyboard Shortcuts Help
<h2>Introduction</h2><p>Groovy supports multiple ways to generate text dynamically including <a class="confluence-link" href="/display/GROOVY/Strings+and+GString#StringsandGString-Strings-GStrings" data-anchor="Strings-GStrings" data-linked-resource-id="2771" data-linked-resource-type="page" data-linked-resource-default-alias="Strings and GString#Strings-GStrings" data-base-url="http://docs.codehaus.org">GStrings</a>, <code>printf</code> if you are using Java 5, and <a class="confluence-link" href="/display/GROOVY/Creating+XML+using+Groovy%27s+MarkupBuilder" data-linked-resource-id="63650" data-linked-resource-type="page" data-linked-resource-default-alias="Creating XML using Groovy's MarkupBuilder" data-base-url="http://docs.codehaus.org">MarkupBuilder</a> 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.</p><h2>Template framework</h2><p>The template framework in Groovy consists of a <code>TemplateEngine</code> abstract base class that engines must implement and a <code>Template</code> interface that the resulting templates they generate must implement.</p><p>Included with Groovy are several template engines:</p><ul><li><code>SimpleTemplateEngine</code> - for basic templates</li><li><code>GStringTemplateEngine</code> - stores the template as writable closures (useful for streaming scenarios)</li><li><code>XmlTemplateEngine</code> - works well when the template and output are valid XML</li></ul><h2>SimpleTemplateEngine</h2><p>Shown here is the <code>SimpleTemplateEngine</code> 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:</p><table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="java" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6amF2YX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>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() </pre></td></tr></table><p>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:</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>$firstname </pre></td></tr></table><p>to this (assuming we have set up a static import for capitalize <strong>inside</strong> the template):</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>${capitalize(firstname)} </pre></td></tr></table><p>or this:</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre><% print city %> </pre></td></tr></table><p>to this:</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre><% print city == "New York" ? "The Big Apple" : city %> </pre></td></tr></table><h4>Advanced Usage Note</h4><p>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 <em>The Big Apple</em> above, we would use:</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre><% print city == "New York" ? "\\"The Big Apple\\"" : city %> </pre></td></tr></table><p>Similarly, if we wanted a newline, we would use:</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>\\n </pre></td></tr></table><p>in any GString expression or scriptlet 'code' that appears inside a Groovy script. A normal "<code>\n</code>" 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</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> </pre></td></tr></table><p>in an external file or</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre> </pre></td></tr></table><p>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.)</p><h2>GStringTemplateEngine</h2><p>As an example of using the <code>GStringTemplateEngine</code>, 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:</p><table class="wysiwyg-macro" data-macro-name="code" data-macro-parameters="title=test.template" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6dGl0bGU9dGVzdC50ZW1wbGF0ZX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>Dear "$firstname $lastname", So nice to meet you in <% out << (city == "New York" ? "\"The Big Apple\"" : city) %>. See you in ${month}, ${signed} </pre></td></tr></table><p>Note that we used <code>out</code> instead of <code>print</code> to support the streaming nature of <code>GStringTemplateEngine</code>. Because we have the template in a separate file, there is no need to escape the backslashes. Here is how we call it:</p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>def f = new File('test.template') engine = new GStringTemplateEngine() template = engine.createTemplate(f).make(binding) println template.toString() </pre></td></tr></table><p>and here is the output:</p><table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="none" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6bm9uZX0&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>Dear "Sam Pullara", So nice to meet you in "The Big Apple". See you in December, Groovy-Dev </pre></td></tr></table><p>You can also plug in other templating solutions, e.g. <a class="confluence-link" href="/display/GROOVY/GFreeMarker" data-linked-resource-id="40697869" data-linked-resource-type="page" data-linked-resource-default-alias="GFreeMarker" data-base-url="http://docs.codehaus.org">GFreeMarker</a>, <a href="http://velocity.apache.org/">Velocity</a>, <a href="http://stringtemplate.org">StringTemplate</a>, <a href="http://beust.com/canvas/">Canvas</a> and others.</p><p>If you wish to combine templating with Ant processing, consider <a href="http://groovytools.sourceforge.net/ant/gpp/">Gpp</a>.</p><h2>Using TemplateServlet to serve single JSP-like HTML files</h2><table class="wysiwyg-macro" data-macro-name="note" data-macro-parameters="title=Mind the gap! Ehm, meaning the difference between Groovlets and Templates." style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e25vdGU6dGl0bGU9TWluZCB0aGUgZ2FwISBFaG0sIG1lYW5pbmcgdGhlIGRpZmZlcmVuY2UgYmV0d2VlbiBHcm9vdmxldHMgYW5kIFRlbXBsYXRlcy59&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="RICH_TEXT"><tr><td class="wysiwyg-macro-body"> </td></tr></table><p>The <a href="http://groovy.codehaus.org/api/groovy/servlet/TemplateServlet.html">TemplateServlet</a> just works the opposite as the <a class="confluence-link" href="/display/GROOVY/Groovlets" data-linked-resource-id="2777" data-linked-resource-type="page" data-linked-resource-default-alias="Groovlets" data-base-url="http://docs.codehaus.org">Groovlets</a>(<a href="http://groovy.codehaus.org/api/groovy/servlet/GroovyServlet.html">GroovyServlet</a>) 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 <code>.groovy</code> file and served by the GroovyServlet (and the GroovyScriptEngine), but after generation, the template is evaluated and responded to the client.</p><p>Here is a simple example <strong>helloworld.html</strong> file which is not validating and does not have a <code>head</code> 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:</p><table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="xml" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6eG1sfQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre><html> <body> <% 3.times { %> Hello World! <% } %> <br> <% if (session != null) { %> My session id is ${session.id} <% } else println "No session created." %> </body> </html> </pre></td></tr></table><p> </p><p>The first Groovy block - a for loop - spans the <code>HelloWorld!</code> text. Guess what happens? And the second Groovy statement prints the servlet's session id - if there is a session avaiable. The variable <code>session</code> is one of some default bound keys. More details reveals the documentation of <a href="http://groovy.codehaus.org/api/groovy/servlet/ServletBinding.html">ServletBinding</a>.</p><p>Here is some sample code using <a href="http://www.eclipse.org/jetty/">http://www.eclipse.org/jetty/</a>s servlet container. With Jetty, dependencies added through Grape, create a tiny web server with the following. To test it, add your above <strong>helloworld.html</strong> file into your current directory and browse <a href="http://localhost:1234/helloworld.html">http://localhost:1234/helloworld.html</a></p><table class="wysiwyg-macro" data-macro-name="code" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGV9&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre>@Grapes([ @Grab(group='org.eclipse.jetty.aggregate', module='jetty-server', version='8.1.7.v20120910'), @Grab(group='org.eclipse.jetty.aggregate', module='jetty-servlet', version='8.1.7.v20120910'), @Grab(group='javax.servlet', module='javax.servlet-api', version='3.0.1')]) import org.eclipse.jetty.server.Server import org.eclipse.jetty.servlet.* import groovy.servlet.* def server = new Server(1234) def context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS) context.resourceBase = "." context.addServlet(TemplateServlet, "*.html") server.start() </pre></td></tr></table><p>Here is a similiar <strong>web.xml</strong> example.</p><table class="wysiwyg-macro" data-macro-name="code" data-macro-default-parameter="xml" style="background-image: url(/plugins/servlet/confluence/placeholder/macro-heading?definition=e2NvZGU6eG1sfQ&locale=en_GB&version=2); background-repeat: no-repeat;" data-macro-body-type="PLAIN_TEXT"><tr><td class="wysiwyg-macro-body"><pre><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> </pre></td></tr></table><h3>Further reading</h3><p><a href="http://www-106.ibm.com/developerworks/java/library/j-pg02155/">Article on templating with Groovy templates</a><br /> <a href="http://www-106.ibm.com/developerworks/java/library/j-pg03155/">Article on templating with Groovlets and TemplateServlets</a><br /> <a href="http://www.jroller.com/melix/entry/freemarker_for_groovy">Blog about combining Groovy and FreeMarker</a></p>
Please type the word appearing in the picture.
Attachments
Labels
Location
Watch this page
< Edit
Preview >
Loading…
Save
Cancel
Next hint
search
attachments
weblink
advanced