Peter Marklund

Peter Marklund's Home

2007-09-12

Rails Tip: Nested Layouts

This is just a feature I always wanted in Rails - nested layouts, i.e. the ability to have one master layout (application.rhtml) for your whole site, and then to have layouts within that that differ from section to section. Today I stumbled across this hack - just a single helper method that allows the use of nested layouts. Sweet. I'll re-post the code here:

module DocHelper
  # Nested layouts, see: http://fora.pragprog.com/rails-recipes/write-your-own/post/144
  def inside_layout(layout, &block)
    @template.instance_variable_set("@content_for_layout", capture(&block))

    layout = layout.include?("/") ? layout : "layouts/#{layout}" if layout
    buffer = eval("_erbout", block.binding)
    buffer.concat(@template.render_file(layout, true))
  end  
end

 

<% inside_layout 'application' do %>
  <div style="font-size: 150%">
    <%= yield %>
  </div>
<% end %>

5 comment(s)

Comments

Peter Marklund said 2008-11-18 12:30:

Here is an alternative approach that seems to work and doesn't require any patches: http://mattmccray.com/archive/2007/02/19/Sorta_Nested_Layouts
--------------------------------------------------------------------------------

cs said 2008-10-06 11:52:

this seem sto be working now: http://fora.pragprog.com/forums/8/topics/2#posts-1052
--------------------------------------------------------------------------------

cs said 2008-10-06 11:48:

sorry, the link to the hack is broken ...
--------------------------------------------------------------------------------

Jon said 2008-09-26 01:16:

Isn't this the same as render :layout => 'partial_with_yield' do .. end?
--------------------------------------------------------------------------------

Vote for John McCain! said 2008-07-29 06:35:

McCain for President!
--------------------------------------------------------------------------------