Insights on Ruby, Git, jQuery, Cappuccino, WordPress, Debian and OS X. Please subscribe if you find something useful!

Rails: Nested Layouts

Posted: June 20th, 2008 | Author: Jerod | Filed under: Ruby | Tags: , , | Comments

Sometimes one layout (application.html.erb) just doesn’t cut it, but you don’t want a separate layout for each controller in your app. You can use the following technique to nest your Rails app’s layouts:

In this example, there are two controllers for a simple todo list manager; lists and tasks

#  application.html.erb
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    <title>TODO >> <%= yield(:title) || "Get things done!" %></title>
    <%= stylesheet_link_tag 'todo' %>
  </head>
  <body>
    <div id="container">
      <p style="color: green"><%= flash[:notice] %></p>
 
      <%= yield :main%>
    </div>
  </body>
</html>

The key here is the yield :main on line 16 which means we can use content_for to put our nested layouts’ output inside the yield. Here is the lists layout:

# in lists.html.erb
 
<% content_for :main do %>
  <div id="lists_container">
    <%= yield %>
  </div>
<% end %>
<%= render :file  => "layouts/application.html.erb" %>

Now your view gets rendered inside this layout’s yield and its all good in the hood. Cheers!