Tutorial :Asp.net MasterPage equivalent in Ruby on Rails, Trying to define a site wide layout


Asp.net WebForms and MVC has a concept of Masterpages which make it easy to define a one time layout for all the page of your site. In Rails I'm struggling to find an equivalent usage pattern or feature.

From what I've read it's really easy to define a layout in every action with:

layout: 'viewname'  

Now that seemed pretty ceremonial to include in every controller so I added:

layout: 'application'  

in the base ApplicationController.

So far this is working ok unless I have a more specific layout in the view pages. Is this common technique for getting a consistent style in your Rails application?


Imagine a simplified blog where we have a controller called PostsController which has two actions: index and show

The index action is called when the user hits http://yourwebsite.com/posts - this action displays all of the available blog posts.

The show action is called when a user gets a specific blog article - i.e. http://yourwebsite.com/posts/article-about-something-interesting

Let's say that we want the index page to have a two column layout and we want the show page for each blog-article to have a three column layout. To achieve this, we would simply define two separate layouts (in app/views/layouts folder) - we'll call the two column layout "application" and we'll call the three-column layout "alternate".

In order to get the index page to use the two-column layout and the show page to use the three-column layout, we could just do the following in our controller:

class PostsController < ApplicationController    def index      @posts = Post.all      render :layout => "application"    end      def show      @post = Post.find(params[:id])      render :layout => "alternate"    end  end  

If we want all actions to use the same layout, we can just do this:

class PostsController < ApplicationController    layout "application"      def index      @posts = Post.all    end      def show      @post = Post.find(params[:id])    end  end  

Finally, if we do not specify which layout we want to use, then Rails will by default, render any layout which has the same name as the resource we are displaying. So in our example, where our resources are called "Posts", if we define a third layout called posts.html.erb (in app/views/layouts) then Rails will automatically use that layout when the user renders any of the actions in the PostsController - providing of course that we have not explicitly asked Rails to render another layout....

Hope it helps,


This PDF book excerpt from Rails for .Net Developers has a pretty good explanation of Rails layouts, along with a comparison to ASP.Net MasterPages. Since it seems to work pretty well, it's probably used fairly often, at least by developers familiar with the master page concept.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »