Last updated by dserodio 4 years ago

Tips and Tricks in Grails

Showing a GSP's generated Groovy code

Add showSource to the URL of the grails controller to see the generated Groovy code from the gsp page. Example:


This feature only works when executing Grails within the "development" environment. More details here

Quick Tip on Markup Builder example is from a Domain object (Book) that contains enum's if you have only simple datatypes then "render as XML" works just fine

String toXML() {
  StringWriter buffer = new StringWriter()
  def xml = new MarkupBuilder(buffer) {
  return buffer.toString() + "\\n"
Keep in mind that the difference between author and pagecount looks like this in the xml
  <pagecount pagecount='99' />
You can see that the pagecount is much more terse but may present challenges on parsing.

Quick Tip on parsing say a Rest service that returns the XML above: This assumes you used an XMLSlurper to parse the text into a GPathResult

static Book fromXML(GPathResult bookXML)
 def book = new Book() = Integer.parseInt( =
 book.pagecount = Integer.parseInt(bookXML.pagecount.@pagecount.text())
 return book

Pay special attention to the use of the "at" symbol to get access to the property on the field as opposed to the field contents.

If you really cared about terse XML in your REST service you might even do this:

String toXML() {
  StringWriter buffer = new StringWriter()
  def xml = new MarkupBuilder(buffer), author:this.authorName, pagecount:this.pagecount){}
  return buffer.toString() + "\\n"
Which would result in XML like this:
<book id='222' author='Toddecus' pagecount='99' />
doesn't help much if your domain object contains a set of sub elements though :)

Enum usage

If you want to use a Enum with a "value" String attribute (a pretty common idiom) in a <select> element, try this:

enum Rating {
    G("G"),PG("PG"),PG13("PG-13"),R("R"),NC17("NC-17"),NR("Not Rated")

final String value

Rating(String value) { this.value = value }

String toString() { value } String getKey() { name() } }

Then add optionKey="key" to your <g:select /> tag. Credit: Gregg Bolinger