Inject Methods/Properties to be available in all GSP Pages

25 / Sep / 2012 by Kushal Likhi 2 comments

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

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. Søren Berg Glasius

    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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *