Switching Grails views
November 22, 2008
This is a repost from my post over at GroovyMag.
I’m planning to do this on a couple other projects, and thought I’d share this with you. It’s not specifically something related to GroovyMag magazine, but is a technique I’m using in a Grails project to make it easy to switch layouts based on the user.
All the default generated views use the meta tag ‘layout’ to point to a GSP file which will get merged with your view file (using sitemesh) to generate the final rendered HTML. Unfortunately these are always hardcoded to ‘main’ rather than a configurable option. So, I’ve taken to modifying the templates used during generation to point to a configuration value.
Run “grails install-templates” then look in src/templates/scaffolding. You’ll see the create/edit/list/show GSP files which are used as the basis for generation.
Edit the files such that the meta line
<meta name=”layout” content=”main” />
looks like this
<meta name=”layout” content=”\${session?.layout?:grailsApplication.config.sitemesh.layout}” />
(Note the Elvis
operator above)
Then edit your grails-app/conf/Config.groovy file to have a line that reads
sitemesh.layout = “main”
If you then generate views for an app, everything will continue to work as it normally does by default; specifically, all the views will use the grails-app/views/layouts/main.gsp as a sitemesh wrapper for rendering.
However, you’re now able to set the layout to something different for each user by setting the session.layout value.
If a user has authenticated and is an administrator, perhaps you’d want to have
session.layout = “admin”
in a controller action, which would use the grails-app/views/layouts/admin.gsp file for rendering views for an admin.
If views for entire controllers require a different view, you should be able to set the global config value for all users by doing something like
grailsApplication.config.sitemesh.layout = “layout2″
in a controller action.
Posted in 



