coderberry

Using Tag Lib Within Controllers and Services

So let’s say you want to utilize the standard grails tag lib of formatNumber within your domain class, controller or service. How would you go about doing it? With the help of a blog post by Lucas Teixeira, I was able to get it working without an issue. Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Book {

  def grailsApplication

  String title
  Float cost

  static constraints = {
    title(blank: false)
    cost(blank: false)
  }

  def String toDisplayString() {
    def g = grailsApplication.mainContext.getBean(
      'org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib'
    )
    return "${title} costs ${g.formatNumber(
      [number: cost, type: "currency", currencyCode: "USD"]
    )}"
  }

}

It’s also simple to utilize your own tag libs as well. Here’s a tag lib that I created to help with XML formatting:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class CommonTagLib {

    static namespace = 'berry'

    def formatXML = { attrs, body ->
        String rawXML = body().toString()
        try {
            def slurpedXML = new XmlSlurper().parseText(rawXML)
            def writer = new StringWriter()
            new XmlNodePrinter(new PrintWriter(writer)).print(slurpedXML)
            def formattedResponse = writer.toString()
            out << formattedResponse
        } catch(Exception e) {
            log.info "Unable to parse XML: ${e.message}"
            out << rawXML
        }
    }

}

So to call this tag lib in the domain class, controller or service, I just need to do the following:

1
2
def berry = grailsApplication.mainContext.getBean('CommonTagLib')
return berry.formatXML("....")

Just make sure that you include the ‘def grailsApplication’ in the beginning.

Comments