Mix tags and text using a MarkupBuilder

The MarkupBuilder provides two methods for including text with the tags; mkp.yield and mkp.yieldUnescaped.

  • mkp.yield is used when you want to escape your html characters.
  • mkp.yieldUnescaped is used when you do not want to escape your html characters.

For example, to create the markup:

<ul>
  <li>Learn more about &lt;html&gt; tags at the 
    <a href='http://www.w3.org/'>W3</a> site.
  </li>
</ul>

We can use:

def builder = new groovy.xml.MarkupBuilder()
 
builder.ul {
    li {
        mkp.yield 'Learn more about <html> tags at the ' 
        a href:'http://www.w3.org/', { 
            mkp.yield 'W3' 
        }
        mkp.yield ' site.' 
    }
}

If we wanted to include some HTML tags in our text then we use the yieldUnescaped method.

For example, to create:

<ul>
  <li>For more <b>great examples</b> visit the 
    <a href='http://codehaus.groovy.org/'>Groovy</a> site.
  </li>
</ul>

We can use:

def builder = new groovy.xml.MarkupBuilder()
 
builder.ul {
    li {
        mkp.yieldUnescaped 'For more <b>great examples</b> visit the ' 
        a href:'http://codehaus.groovy.org/', { 
            mkp.yield 'Groovy' 
        }
        mkp.yield ' site.' 
    }
}
You can leave a response, or trackback from your own site.

Leave a Reply