john renfrew
john renfrew

Reputation: 413

Groovy markupbuilder tags

Is there a way to modify the code from a previous answer

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def builder = new MarkupBuilder(writer)

def awaiting = ['one', 'two', 'three']

builder.html {
    ul {
        awaiting.each { 
            li(it.toString())
        }
    }
}

println writer.toString()

so that if you add a tag instead that you send it - like

    builder.html{
tag{
    awaiting.each{}
    }
} return result

could be 'ol' or 'ul' for example

Upvotes: 2

Views: 1798

Answers (2)

hlg
hlg

Reputation: 1331

You could also use invokeMethod which is more explicit then the above, albeit a little bit longer.

builder.html {
  invokeMethod(tag) {
    awaiting.each { 
      li it
} } }

Upvotes: 0

gizmo
gizmo

Reputation: 11909

You can rely on the GStrings and the fact that you can call a function by its string value.

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def builder = new MarkupBuilder(writer)

def awaiting = ['one', 'two', 'three']
def tag = 'ol'

builder.html {
    "$tag" {
        awaiting.each { 
            li(it.toString())
        }
    }
}

println writer.toString()

Upvotes: 3

Related Questions