Peter Marklund

Peter Marklund's Home

Wed September 12, 2007
Programming

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 %>

Comments

Vote for John McCain! said over 5 years ago:

McCain for President!

--------------------------------------------------------------------------------

Jon said over 5 years ago:

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

--------------------------------------------------------------------------------

cs said over 5 years ago:

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

--------------------------------------------------------------------------------

cs said over 5 years ago:

this seem sto be working now:

http://fora.pragprog.com/forums/8/topics/2#posts-1052

--------------------------------------------------------------------------------

Peter Marklund said over 5 years ago:

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

--------------------------------------------------------------------------------