tags:

views:

1451

answers:

2

When using Groovy MarkupBuilder, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag "text" to do the output. Is there a better way to write this code?

li{
  text("${type.getAlias()} blah blah ")
  function1(type.getXYZ())
  if (type instanceof Class1) {
    text(" implements ")
    ft.getList().each{ 
      if (it == '') return
      text(it) 
      if (!function2(type, it)) text(", ")
    }
  }
}
A: 

Include a method:

void text(n){
    builder.yield n
}

Most likely you (I) copied this code from somewhere that had a text method, but you didn't also copy the text method. Since MarkupBuilder accepts any name for the name of a tag and browsers ignore unknown markup, it just happened to work.

+1  A: 

Actually, the recommended way now is to use mkp.yield, e.g.,

src.p {
    mkp.yield 'Some element that has a '
    strong 'child element'
    mkp.yield ' which seems pretty basic.'
}

to produce

<p>Some element that has a <strong>child element</strong> which seems pretty basic.</p>
Hank Gay