Reputation: 1970
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:
${ UtilClass.getDynamicText() }
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
Reputation: 3557
This is how I would do it:
grails install-templates
\src\templatesscaffolding
class ${className}Controller extends NewController
You can now use the method in every class and gsp.
Upvotes: 0
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
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
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