Over a million developers have joined DZone.

Groovy Goodness: Nested Templates with MarkupTemplateEngine

DZone's Guide to

Groovy Goodness: Nested Templates with MarkupTemplateEngine

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

Since Groovy 2.3 we can use the MarkupTemplateEngine to generate XML/HTML. We can write our templates using a builder syntax. Inside our templates we can define nested templates. These nested templates contain builder syntax code and can use objects that are passed as attributes to the nested template. To invoke a nested template we must use the fragment method and pass a Map with attributes that is used in the nested template. We can re-use nested templates inside our template.

In the following sample code we define two nested templates: faIcon and list. Inside our template we use the fragment method to call these nested templates and we set values to the attributes that are used in the nested templates:

import groovy.text.*
import groovy.text.markup.*

// Create configuration for engine.
TemplateConfiguration config = new TemplateConfiguration(
    useDoubleQuotes:true, expandEmptyElements: true)

// Create engine with configuration.
MarkupTemplateEngine engine = new MarkupTemplateEngine(config)     

// Create template with template fragment
// to display the FontAwesome markup.
Template template = engine.createTemplate('''

    // Nested template to generate
    // FontAwesome markup. 
    // The fragment expect a model attribute
    // with the name icon.
    def faIcon = 'span(class: "fa fa-${icon}")'
    // Nested template to generate
    // a unordered list for given items,
    // specified with the items model attribute.
    String list = """ul {
        items.each { item ->
            li item
    // Use fragment method.
    fragment list, items: ['A', 'B', 'C']
    ul {
        ['cloud', 'home', 'pencil'].each { iconValue ->
            // Generate output with predefined
            // fragment faIcon. Pass value
            // for model attribute icon.
            // We must use ${stringOf{...}} because we apply
            // the fragment as inline element. 
            li "${stringOf {fragment(faIcon, icon: iconValue)}}"
    // Reuse fragment in other parts of the template.
    p "This is a ${stringOf {fragment(faIcon, icon: 'cog')}} settings icon."

// Render output for template.
Writer writer = new StringWriter()                          
Writable output = template.make([:])  
String result = writer.toString()

// This is what we would expect as a result.
def expected = $/\
<li><span class="fa fa-cloud"></span></li>\
<li><span class="fa fa-home"></span></li>\
<li><span class="fa fa-pencil"></span></li>\
<p>This is a <span class="fa fa-cog"></span> settings icon.</p>\

assert result == expected

Code written with Groovy 2.3.6.

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}