Skip to content

Instantly share code, notes, and snippets.

@mattbrictson
Last active August 16, 2023 15:33
Show Gist options
  • Star 26 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattbrictson/9240548 to your computer and use it in GitHub Desktop.
Save mattbrictson/9240548 to your computer and use it in GitHub Desktop.
Simpler nested layouts in Rails using the parent_layout helper
<%= render("shared/navbar") %>
<div class="container">
<%= render("shared/alerts") %>
<%= render("shared/page_header") %>
<%= yield %>
<%= render("shared/footer") %>
</div>
<% parent_layout "base" %>
<!DOCTYPE html>
<html>
<head>
<%= stylesheet_link_tag("application", "data-turbolinks-track" => true) %>
<%= javascript_include_tag("application", "data-turbolinks-track" => true) %>
<%= yield(:head) %>
<meta charset="utf8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<%= csrf_meta_tags %>
<title>
<%= yield(:title) + " – " if content_for?(:title) %>
RailsStarter
</title>
</head>
<body>
<%= yield %>
</body>
</html>
module LayoutsHelper
# Used to achieve nested layouts without content_for. This helper relies on
# Rails internals, so beware that it make break with future major versions
# of Rails. Inspired by http://stackoverflow.com/a/18214036
#
# Usage: For example, suppose "child" layout extends "parent" layout.
# Use <%= yield %> as you would with non-nested layouts, as usual. Then on
# the very last line of layouts/child.html.erb, include this:
#
# <% parent_layout "parent" %>
#
def parent_layout(layout)
@view_flow.set(:layout, output_buffer)
output = render(template: "layouts/#{layout}")
self.output_buffer = ActionView::OutputBuffer.new(output)
end
end
@collimarco
Copy link

This should be added to Rails core, would be very useful

@Petecass
Copy link

Petecass commented Dec 3, 2016

πŸŽ‰ πŸ‘ πŸ‘

@romkaspb
Copy link

Thank you, really very useful!

@leouz
Copy link

leouz commented Jan 16, 2018

exactly what I was looking for, thank you!

working perfectly on rails 5.1.4 πŸ‘

@fgblomqvist
Copy link

Doesn't render the output (line 14 in the helper) for me on Rails 5.1.6. As in, only the content gets rendered, not any of the templates (neither parent nor child). The correct HTML ends up in output, but is for some reason never used. Not skilled enough in Rails to know why.

@vsppedro
Copy link

vsppedro commented Dec 30, 2019

Thanks! πŸ‘ πŸ‘ πŸ‘

Working perfectly on rails 6.0.1!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment