tags:

views:

170

answers:

3

I'm building a CMS as a learning exercise in Grails and would like to give content managers the ability to choose between different HTML page structures (e.g. 2 column, 3 column, etc).

Grails Layouts seem like a logical choice but is it possible for a Grails controller to explicitly name which layout will be used for rendering? Ideally there would be a layout option to the render method, per Ruby on Rails but I don't see anything like it.

It seems like it might be possible using the applyLayout method by passing the name of the layout but this requires each GSP page to explicitly request layout (annoying overhead per-page) rather than using Layout by Convention.

Any ideas?

A: 

I don't know of a way to do it per-action, but you can specify it at the controller level, e.g.

class FooController {

   static layout = 'cms'

   def index = {}
   def foo = { ... }
   def bar = { ... }
}
Burt Beckwith
I saw that one too but I need it per-action, since the layout will be user account specific.
maerics
+3  A: 

Why not just pass it in the model and have it rendered in the meta tag that determines the layout?

<meta name="layout" content="${myValueFromController}"/>

I haven't tried it, but I think it'd work.

Ted Naleid
This solution would work but I'd like to avoid typing the boilerplate `<html><head>...` wrappers for each view.
maerics
+1  A: 

Hey, I think i have a solution for you: Just use Ted Naleids idea in combination with the afterInterceptor of your controller:

foo.gsp:

<meta name="layout" content="${actionLayout}" />

FooController.groovy:

class FooController {

  def index = { 
    // do awesome stuff
  }

  def afterInterceptor = { model ->
    model.actionLayout = actionName}
  }
}

The only thing you have to do now, is naming your layouts like your actions or create some other naming logic.

air_blob
Grails does something similar out of the box. If all you want is a layout based on the current controller and action name, you can just not have a meta layout tag and grails will look for views/layouts/${controller}/${action}.gsp. Your suggestion would work if the desire was to share the same layout for every action of the same name (ex: a list layout).
Ted Naleid
Wow, didn't know that - thanks!
air_blob