David
David

Reputation: 1970

Add method to be available in all Views

I would like to have a method available to all Views in my app.

I would like to be able to make calls like this:

<span>${ getDynamicText() }</span>

The most obvious ways (to me) to implement this are:

  1. Call the method in the controller and and pass it to the View.
  2. Make the method static on some Util class and call it from the code ${ UtilClass.getDynamicText() }
  3. Using meta programming to somehow make the method available to all Views.

The benefit of #3 is that the change would only have to be made in one place. #1 would have to be made in each controller action; and #2 would need an import on every View page which wants to use the method.

So is there a way to add a method to be available to all views in my app?

I have to admit I don't know in a lot of detail how .gsp files are processed behind-the-scenes so maybe they don't have a corresponding class and therefore can't be manipulated in this way. Links to good articles/docs will get extra good karma.

Upvotes: 0

Views: 168

Answers (4)

Kristof Mols
Kristof Mols

Reputation: 3557

This is how I would do it:

  • Add a new class to your controllers folder containing your method
  • Do a grails install-templates
  • Navigate to the templates: \src\templatesscaffolding
  • Add the extends part to the controller template: class ${className}Controller extends NewController
  • re-generate your controllers

You can now use the method in every class and gsp.

Upvotes: 0

D&#243;nal
D&#243;nal

Reputation: 187379

The recommended way to reuse functionality across GSPs is to define it as a tag, e.g.

class MyTagLib {

  static namespace = 'my'

  def dynamicText = {attrs ->
    out << 'not very dynamic'
  }
}

You can then call this tag in a GSP using:

<my:dynamicText/>

Upvotes: 2

Igor Artamonov
Igor Artamonov

Reputation: 35951

4th way: make a class/service that have method '.getDynamicText' and put it's intance into request at before filter ( request.setAttribute('x', myDynamicTextGeneratorObject) )

Now you can use x.dynamicText in any GSP

Upvotes: 1

Burt Beckwith
Burt Beckwith

Reputation: 75681

GSPs are compiled into classes that extend org.codehaus.groovy.grails.web.pages.GroovyPage, so you can add methods to that metaclass and they'll be available to all GSPs. The best place to do this is in BootStrap.groovy (or in a plugin's doWithDynamicMethods closure):

import org.codehaus.groovy.grails.web.pages.GroovyPage

class BootStrap {

   def init = { servletContext ->
      GroovyPage.metaClass.getDynamicText = { ... }
   }
}

Upvotes: 3

Related Questions