开发者

Can layouts be chosen by Grails controllers?

开发者 https://www.devze.com 2022-12-26 15:41 出处:网络
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).

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 a开发者_如何学编程nything 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?


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.


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 = { ... }
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号