Ruby on Rails: Choose Multiple Layouts for the Same Controller

The trick to choose multiple layouts for the same controller is to define the layout as a method and then choose the layout depending on the action_name. Here’s the sample code for a controller which uses the layout site-index for the action index and the layout site for rest of the actions.

class SiteController < ApplicationController
  
  def index
  end
  
  def about
  end

  def help
  end
  
  layout :choose_layout
  
  def choose_layout
    if action_name == 'index'
      return 'site-index'
    else
      return 'site'
    end
  end
  
end

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.