Skip to content

How to specify multiple layouts within the same controller in Ruby on Rails

Posted on 03 October 2006

Using more than one layout in a controller is as simple as placing the following code in your controller:

layout :choose_layout

private
def choose_layout    
  if [ 'signup', 'login' ].include? action_name
    'login'
  else
    'admin'
  end
end

When Rails goes to select the layout it wont find one named "choose_layout", so it will look for an action with that name instead.

The action checks if the Rails variable action_name (which contains the name of the current action) matches either 'signup' or 'login'. If this is true then the 'login' layout is rendered otherwise 'admin' is.

View the snippets archive ››

7 comments made

sal commented on 14 Jun 07 at 22:50

schweet!

Joe commented on 05 Nov 07 at 04:39

This is great. I tried many different ways to accomplish it and never could get it to work. Glad I found this or I will still be forced to use a single layout.

Mike commented on 14 Nov 07 at 00:47

Thanks a bunch – that’s really cool!

Jon Sidnell commented on 01 Dec 07 at 09:47

Absolutely spot on! Exactly what I needed for a current project. Thanks!

Mike Tunnicliffe commented on 09 Dec 07 at 19:31
This approach looks superior to what I found in the Rails docs, which was to use:

layout :default_layout def some_action render :action => “some_action”, :layout => “different_layout” end

Dan Sweeney commented on 05 Apr 08 at 14:10

Just wanted to say thanks… this is a handy snippet!

Michael Madison commented on 12 May 08 at 02:24

Holy crap! You’re a genius! Awesome man.

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com