Howardism Musings from my Awakening Dementia
My collected thoughts flamed by hubris
Home PageSend Comment

Useful Taglibs for Grails

The Taglibs mechanism for Grails is pretty easy. However, I was surprised that a few useful tags are part of the default implementation.††Version 1.0.2 as of this writing So I thought I would share a couple…

Grails comes with <g:link> which allow you to optionally specify the "controller", the "action", the "id", etc. If any of those aren't given, it makes some good guesses based on where the GSP file that contains the tag lives. Makes sense. But why isn't there a <g:button> tag which does the same thing, but wraps up the reference with an HTML <input type="button"> tag instead?

def button = { attrs ->
  def writer = out
  writer << '<input type="button" onclick="location.href=\''
  // create the link 
  if(request['flowExecutionKey']) {
    if(!attrs.params) attrs.params = [:]
    attrs.params."_flowExecutionKey" = request['flowExecutionKey']
  }

  writer << createLink(attrs).encodeAsHTML()
  writer << '\'"'
  // process remaining attributes
  attrs.each { k,v ->
    writer << " $k=\"$v\""
  }
  writer << '/>'
}

Note: This code was heavily adapted (read stolen) from the implementation of <g:link>.

I ran into a situation where I had a "list"-type table with a field that could contain a large amount of text (from a text blog in the database). I wanted to print out the first part of it, but wanted it readable. So, I wanted the string chopped, but not in a middle of a word. Maybe even at the end of a complete sentence.

So while this tag isn't particularly complicated, it might help someone new to Groovy.

// Limits the amount of text that possibly could
// be displayed. A null is alright to pass in.
// <g:shortString text="${message}" length="80"/>

def shortString = { attributes ->
  String text = attributes.text
  int length  = attributes.length ? Integer.parseInt(attributes.length) : 100

  if ( text ) {
    if ( text.length() < length )
        out << text.encodeAsHTML()
    else {
        text = text[0..length-1]
        if ( text.lastIndexOf('. ') != -1 )
            out << text[0 .. text.lastIndexOf('. ') ]
        else if ( text.lastIndexOf(' ') != -1 )
            out << text[0 .. text.lastIndexOf(' ')] << '&hellip;'
        else
            out << text << '&hellip;'
    }
  }
}
Tell others about this article:
Click here to submit this page to Stumble It