Inject Methods/Properties to be available in all GSP Pages
Hi,
There could be cases where we would need to inject some methods or properties in all GSP pages.
As we know that the GSP pages extends GroovyPage class, hence injecting properties/methods in GroovyPage class can solve out purpose.
Example: Lets add appVersion property and a method to provide logo link irrespective of the knowledge of containing module.
[java]
//Adding property
GroovyPage.metaClass.appVersion = "my app Version"
//Adding the method to give the logo link
GroovyPage.metaClass.logoLink = {
resource(dir: ‘images’, file: ‘logo.png’,plugin: ‘my-module-containing-logo’)
}
[/java]
Now in Any GSP in the application we can do:
[html]
<div>
<img src="${logoLink()}" />
<p>App Version:- ${appVersion}</p>
</div>
[/html]
Hope It Helps!
Kushal Likhi
ok, it didn’t like my gsp
so I’m rewriting it to
<img src=”${logoLink}”/>
Hi,
Great tips!
However, turning your logoLink into a property would make it even more Groovy:
GroovyPage.metaClass.getLogoLink = {
resource(dir: ‘images’, file: ‘logo.png’,plugin: ‘my-module-containing-logo’)
}
Then your GSP would be
Best regards,
Søren