providence
providence

Reputation: 29463

Use a layout for a specific action

If I would like to use a layout for a certain action (say, the show action) that is different from the layout declared at the top of the controller.rb file, how could I do this? This must be possible in rails, but I cannot seem to find anything about it.

Upvotes: 36

Views: 13676

Answers (3)

Martin K.
Martin K.

Reputation: 1258

Following example applies desired layout to specific action, otherwise, it uses default layout (layouts/application.html.erb).

class ArticlesController < ApplicationController
   layout "article_editor", only: [:new, :edit]

   def index
     # default layout
   end

   def new
     # article_editor layout
   end

   def edit
     # article_editor layout
   end
end

Upvotes: 0

Kyle Macey
Kyle Macey

Reputation: 8154

layout 'layout', :only => [:first_action, :second_action]
layout 'second_layout', :only => [:third_action, :fourth_action]

Don's is right as well, just depends on your application which is more DRY (or DRY-er?)


EDIT My previous code is mistaken. You cannot specify the layout function multiple times. I found this solution online for dynamic layout rendering:

class OrdersController < BaseController
  layout :determine_layout

private
  def determine_layout
    %w(new).include?(action_name) ? "some_layout" : "public"
  end
end

Source: apidock.com/rails/Actio...

Upvotes: 37

Don Roby
Don Roby

Reputation: 41127

  render :layout => 'otherlayout'

Upvotes: 44

Related Questions