Custom Implicit Variables in GSPs (Kevin Burke)
Grails, Groovy, Kevin Burke June 1st, 2008
Kevin Burke writes:
I really should start every post with “groovy is a really swell language”. You can do some pretty cool things with it.
Anyway, I had a desire to have an variable implicitly available in all of my GSP’s so that I didn’t have to wrap certain blocks in a tag that made the variable available. There were a couple of reasons for this. The first is that if an exception was thrown in the block of code, the stack trace would indicate that it was coming from my custom tag. More importantly however it was a real pain in the tuckus to have to litter my GSP’s with a tag that simply introduced a variable into the scope. After several attempts to hijack the page scope before the page was rendered I settled on the following:
GroovyPage.metaClass .getCurrentUser = { -> ctx.authenzedManager .currentUser ( ) }As it turns out every page extends GroovyPage which is just a groovy script. So you can add methods using it’s metaClass to add all kinds of functionality. This might be a good way for plugins to add sort of helper methods, since, unlike tags, it will actually return a value and not write it to out. Anyway, by adding getCurrenUser I can now call ${currentUser.whatever} from my GSP. It makes me happy.
Rock over London. Rock on Chicago.
5 Responses to “Custom implicit variables in GSP’s”
Tags: Grails, Groovy, Kevin Burke
About
June 2nd, 2008 at 6:15 am Nice. Just one note, tags actually return their value when they’re called as a method such as createLink(action:’foo’)
June 2nd, 2008 at 7:01 am Nice trick, that MOP stuff is really powerful.
June 2nd, 2008 at 7:54 am Graeme: That’s very true. Sorry for spreading misinformation. Oh well, still fun stuff anyway.
Shawn: I don’t know what I’d do without it.
June 3rd, 2008 at 10:30 pm Where do you put this code in a Grails app? In the config.groovy? maybe bootstrap.groovy?
June 4th, 2008 at 8:05 am esbium: BootStrap would be a good place to put it. I happen to be using a plugin in this example.