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 index
render :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
<!–[if !supportLists]–>
- 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)
Hi Chirag,
Thanks for the explanation on Rails layouts! It really helped me manage my layouts!
For the nested layouts, instead of defining a method in controllers to return the controller names, I used a built-in controller method called controller_name to refer to each controller’s partial.
I explained this further in my blog: rubynerds.blogspot.com under “Nested layouts in Rails”
Looks like an old post but is very much appreciated by me. I knew there had to be a better way to do this than with a plugin. I just could not find a simple way as I’m still fairly new to RoR. Thanks much Chirag