Ruby-on-rails – Rails layouts per action

ruby-on-rails

I use a different layout for some actions (mostly for the new action in most of the controllers).

I am wondering what the best way to specify the layout would be? (I am using 3 or more different layouts in the same controller)

I don't like using

render :layout => 'name'

I liked doing

layout 'name', :only => [:new]

But I can't use that to specify 2 or more different layouts.

For example:

When I call layout 2 times in the same controller, with different layout names and different only options, the first one gets ignored – those actions don't display in the layout I specified.

Note: I'm using Rails 2.

Best Answer

You can use a method to set the layout.

class MyController < ApplicationController
  layout :resolve_layout

  # ...

  private

  def resolve_layout
    case action_name
    when "new", "create"
      "some_layout"
    when "index"
      "other_layout"
    else
      "application"
    end
  end
end