August 7, 2014

Groovy Goodness: Nested Templates with MarkupTemplateEngine

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.