Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Nested Templates with MarkupTemplateEngine

DZone's Guide to

Groovy Goodness: Nested Templates with MarkupTemplateEngine

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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([:])  
output.writeTo(writer)   
String result = writer.toString()


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

assert result == expected

Code written with Groovy 2.3.6.

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}