Nested Layouts
Published almost 6 years ago

Don’t think the nested layouts get any simpler in Rails.

module ApplicationHelper
  def parent_layout(layout)
    @content_for_layout = self.output_buffer
    self.output_buffer = render(:file => "layouts/#{layout}")

Now using the parent_layout helper method inside your layouts for nesting :

# items.html.erb
<h1>Just my items</h1>
<%= yield %>

<% parent_layout 'master' %>

and the parent layout of items – the master layout :

# master.html.erb
<html xmlns="" xml:lang="en" lang="en">
  <head><title>Hello World</title></head>
    <%= yield %>

Now, the items layout will always be wrapped under the master layout. Just make sure that the parent_layout call is always on the last line using <%. This technique also works for nesting deeper than a single level.