Rails Layout

In a Ruby on Rails application you might have several controllers working together. When you generate a controller Rails also creates a layout for that controller. So if you generate three controllers you also have three layout rthml files under you app/views/layouts directory. If all these controllers are working together for the same application it can be assumed that they have the same look and feel which needs to be repeated in each of the layout rhtml files, well it doesn’t have to. One of the guiding principles of Rails is DRY, Don’t Repeat Yourself. It wouldn’t be a good idea to repeat the look and feel of you application in the layout for each controller.

You can use the render function’s layout symbol to specify which template should be used to display the results of a given controller action. Here is an example of that:

class IndexController < AppplicationController
   def index
      render :layout => 'mylayout'
   end

   def list
   end
end

In this example, the index action will be rendered using the app/views/layout/mylayout.rhtml layout. For the list action the app/views/layout/index.rhtml layout, the default layout for this controller, will be used to render the action’s HTML.

If you want to use a given layout for all of a controller’s actions you can do the following:

class IndexController < AppplicationController
   layout 'mylayout'

   def index
   end

   def list
   end
end

Technorati Tags: , ,