Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting layouts in Rails

Is it possible to nest layouts in Rails 3.2? I'd like to create a generic layout used by application.html.erb and allow a couple views in the application to use it. I found the Nested Layouts ruby gem, but it hasn't been updated in four years. It would be awesome if I could do something like the following in my application.html.erb file:

<% inside_layout 'html5_boilerplate' do %>
  <div id="container">
    <%= yield %>
  </div>
<% end %>
like image 745
LandonSchropp Avatar asked Dec 09 '12 00:12

LandonSchropp


3 Answers

I found an easy solution in this blog post.

In my ApplicationHelper, I added the following:

def parent_layout(layout)
  @view_flow.set(:layout, output_buffer)
  self.output_buffer = render(:file => "layouts/#{layout}")
end

In application.html.erb, I added:

<% parent_layout 'html5_boilerplate' %>
like image 178
LandonSchropp Avatar answered Oct 27 '22 13:10

LandonSchropp


I tried a few of these, but none worked for me in Rails 4. But with a little inspiration from the nested_layouts gem, I came up with the following simple fix:

module ApplicationHelper
  def inside_layout(layout, &block)
    layout = "layouts/#{layout}" unless layout =~ %r[\Alayouts/]
    content_for :content, capture(&block)
    render template: layout
  end
end

Then I revised my layouts/application.html.erb template to be similar to this:

<html>
  <body>
    <div id="content">
      <%= content_for?(:content) ? yield(:content) : yield %>
    </div>
  </body>
</html>

Now I can declare a nested layout like this:

# app/views/layouts/blog.html.erb
<%= inside_layout 'application' do %>
  <div id="blog_container">
    <%= yield %>
  </div>
<% end %>

Hope this helps!

like image 26
flintinatux Avatar answered Oct 27 '22 14:10

flintinatux


You can use the content_for method as described in the official Rails guide.

like image 1
BvuRVKyUVlViVIc7 Avatar answered Oct 27 '22 15:10

BvuRVKyUVlViVIc7