Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can layouts be chosen by Grails controllers?

Tags:

layout

grails

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?

like image 836
maerics Avatar asked Apr 07 '10 21:04

maerics


4 Answers

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.

like image 71
Ted Naleid Avatar answered Nov 01 '22 03:11

Ted Naleid


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 = { ... }
}
like image 38
Burt Beckwith Avatar answered Nov 01 '22 03:11

Burt Beckwith


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.

like image 22
codeporn Avatar answered Nov 01 '22 03:11

codeporn


Maybe I'm missing something, but couldn't this be easily solved with a little taglib love...?

E.g.

<g:if test="${controllerName == 'xyzController'}">
    <meta name="layout" content="xyzLayout"/>
</g:if>
<g:else>
    <meta name="layout" content="abcLayout"/>
</g:else>

I use something similar to this for determining which tab should have a "selected" class applied to it within my layouts. This allows me to keep all of my navigational html within the layout while still getting highlighting. A bit different than what you are asking for, but it seems like it could (possibly?) still work...

like image 2
James Avatar answered Nov 01 '22 02:11

James