I have an application with a global application layout file application.html.haml
. I then have multiple "controller stacks": for our main site, our admin portal, and our business site. For each of these, controllers are within a module and all inherit from the same BaseController
. Each stack has it's own layout file. Within the stack, some controllers have layout files as well.
I would like all views (unless otherwise specified) to render inside multiple levels of nested layouts : application, "stack", "controller".
For example, for the Site::BlogController#show
action, I'd like rails to render:
/site/blog/show.html.haml
inside /layouts/site/blog.html.haml
inside /layouts/site.html.haml
inside /layouts/application.html.haml
I am having difficulty understanding how to insert /layouts/site.html.haml
into the stack. It appears as though automatically, rails will render the action inside the controller layout inside the application layout, however, I can't see how to "insert" layouts into the render stack.
Any help is greatly appreciated, however, I have read all the rails guides to no avail, so a link to http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts will not really be helpful.
if you create a helper like this:
then you can define sublayout like this:
these layouts can be used like normal layouts.
more: http://www.requests.ch/blog/2013/10/30/combine-restful-rails-with-nested-layouts/
You can create a partial with a yield in it.
_my_sub_layout.html.erb:
In some other view or even in your main layout application.html.erb render the partial as a layout:
I guess the simplest way to do it is by adding this line of code in the parent of a nested layout:
you could add as many nested layouts as you want by only changing the path directory of the next layout to be rendered.
note: make sure your nested layout is named _layoutname.whatever and that your nested layout has a yield inside
I reread the link i posted ( http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts ) and realized I missed a key detail.
so, in
Site::BaseController
I have a call tolayout 'site'
and in/layouts/site.html.haml
I haveThen in
Site::BlogController
which extendsSite::BaseController
I havelayout 'site/blog'
and in/layouts/site/blog.html.haml
I haveThis then renders the layouts nested as described in the question. Sorry for missing this in my question. I should've read closer.
I've done similar, but only used 1 level of sublayouts. Can easily be tweaked to allow multiple levels.
In controllers/application_controller.rb:
In controller (for example blog_controller.rb):
In layouts/application.html.erb rather than
<%=yield%>
:Make a partial
layouts/_blog.html.erb
:Repeat for other controller & sub layouts.
EDIT: If you need to do this on a per-action basis: