Ad-Hockery

ad-hockery: /ad·hok'@r·ee/, n. Gratuitous assumptions... which lead to the appearance of semi-intelligent behavior but are in fact entirely arbitrary. [Jargon File]

Optional Tag Bodies

Sometimes you may want to implement a Grails GSP tag that has an optional body. Grails tag closures take one or two arguments, the first a map of the attributes passed to the tag the second a Closure representing the tag body. Even if the tag was not invoked with a body the second argument is not null so doing this does not work:

1
2
3
4
5
6
7
def myTag = { attrs, body ->
  if (!body) {
      // render a default body
  } else {
      // render the supplied tag body
  }
}

It turns out that if the tag did not have a body the argument passed to the Closure is always the same constant, so what you can do is:

1
2
3
4
5
6
7
8
9
import org.codehaus.groovy.grails.web.pages.GroovyPage

def myTag = { attrs, body ->
  if (body.is(GroovyPage.EMPTY_BODY_CLOSURE)) {
      // render a default body
  } else {
      // render the supplied tag body
  }
}

Comments