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 %>
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' %>
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!
You can use the content_for
method as described in the official Rails guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With