Rails: Nested Layouts
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
1 # application.html.erb 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 4 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 5 6 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 7 <head> 8 <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> 9 <title>TODO >> <%= yield(:title) || "Get things done!" %></title> 10 <%= stylesheet_link_tag 'todo' %> 11 </head> 12 <body> 13 <div id="container"> 14 <p style="color: green"><%= flash[:notice] %></p> 15 16 <%= yield :main%> 17 </div> 18 </body> 19 </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:
1 # in lists.html.erb 2 3 <% content_for :main do %> 4 <div id="lists_container"> 5 <%= yield %> 6 </div> 7 <% end %> 8 <%= render :file => "layouts/application.html.erb" %>
Now your view gets rendered inside this layout’s yield and its all good in the hood. Cheers!
0 comments
