Layout basics
Here’s Duane Johnson’s concise explanation of how layouts generally work in Rails. To summarize this blog article, layouts occur at 2 levels (applciation-wide or controller-wide) by default:
- The entire Rails application (all views of all controllers) will use this layout:
views/layouts/application.rhtml
- All views within a single controller will use this layout. For example, the layout for weclome_controller.rb will use this layout. Notice, the ‘_controller’ is left off for the layout:
views/layouts/welcome.rhtml
- Use this code if you want to use a different layout than one of the two default layouts described above. This code will go in the action (index, in this case) corresponding to the view (index.rhtml)
def indexrender :layout => ‘alternative_layout’
end
When using Rails layouts, the final page is rendered by using <%= yield %> in the layout. With <%= yield %>, the view is placed inside the layout during runtime. For example, the application-wide layout application.rhtml could contain the following:
<title>Layout Example</title>
</head>
<body>
<%= yield %>
</body>
</html>
The view (e.g. index.rhtml) for weclome_controller.rb could look something like this:
<b> Hello World </b>
This would render the following final .html page when you enter http://localhost:3000/welcome in your browser:
<title>Layout Example</title>
</head>
<body>
<b> Hello World </b>
</body>
</html
Nested Layouts
To create nested layouts (master layout > sublayout > view), I found the following 2 options
- Using partials and qualifying methods as described in Matt McCray’s blog. Matt’s got an example Rails app that you can download and try. Also here’s a more visual layout of the code that he explains:
- Using the nested-layout plugin
I prefer the first method because its pretty simple and uses inherit Rails methods instead of a plugin that could end up being more maintenance and possibly inflexible later on.
Last, here’s a really good write-up for web designers transitioning to Rails (includes basics about MVC, rhtml, ERB, etc)
