Custom implicit variables in GSP’s

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:

  1. 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.

9 Responses to “Custom implicit variables in GSP’s”

  1. Graeme Rocher Says:

    Nice. Just one note, tags actually return their value when they’re called as a method such as createLink(action:’foo’)

  2. Shawn Hartsock Says:

    Nice trick, that MOP stuff is really powerful.

  3. Kevin Burke Says:

    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.

  4. esbium Says:

    Where do you put this code in a Grails app? In the config.groovy? maybe bootstrap.groovy?

  5. Kevin Burke Says:

    esbium: BootStrap would be a good place to put it. I happen to be using a plugin in this example.

  6. Groovy on Grails » Blog Archive » Custom Implicit Variables in GSPs (Kevin Burke) Says:

    […] Kevin Burke writes: […]

  7. Graeme Rocher Says:

    Btw Kevin make sure you add your blog to groovyblogs.org if you haven’t already

  8. Tamaz Says:

    It’s fun. ATP Subscribe to the RCC perhaps

  9. Ronnie Santana Says:

    q3em2qal94wbxpp8

Leave a Reply