Multiple Level Nested Layout in Rails 3 Multiple Level Nested Layout in Rails 3 ruby ruby

Multiple Level Nested Layout in Rails 3


I reread the link i posted ( http://guides.rubyonrails.org/layouts_and_rendering.html#using-nested-layouts ) and realized I missed a key detail.

<%= render :file => 'layouts/application' %>

so, in Site::BaseController I have a call to layout 'site' and in /layouts/site.html.haml I have

= content_for :footer do   -#Content for footer= render :file => 'layouts/application'

Then in Site::BlogController which extends Site::BaseController I have layout 'site/blog' and in /layouts/site/blog.html.haml I have

=content_for :header do  %h1 HELLO WORLD!= render :file => 'layouts/site'

This then renders the layouts nested as described in the question. Sorry for missing this in my question. I should've read closer.


if you create a helper like this:

# renders a given haml block inside a layoutdef inside_layout(layout = 'application', &block)  render :inline => capture_haml(&block), :layout => "layouts/#{layout}"end

then you can define sublayout like this:

= inside_layout do  # nested layout html here  = yield

these layouts can be used like normal layouts.

more: http://www.requests.ch/blog/2013/10/30/combine-restful-rails-with-nested-layouts/


I've done similar, but only used 1 level of sublayouts. Can easily be tweaked to allow multiple levels.

In controllers/application_controller.rb:

def sub_layout  nilend

In controller (for example blog_controller.rb):

def sub_layout  "blog"end

In layouts/application.html.erb rather than <%=yield%>:

<%= controller.sub_layout ? (render :partial => "/layouts/#{controller.sub_layout}") : yield %>

Make a partial layouts/_blog.html.erb:

...code  <%=yield%>...code

Repeat for other controller & sub layouts.

EDIT:If you need to do this on a per-action basis:

def sub_layout  {    'index' => 'blog',    'new' => 'other_sub_layout',    'edit' => 'asdf'  }[action_name]end