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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}