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.
Comments left...
schweet!
sal at 14 Jun 07 at 22:50
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.
Joe at 05 Nov 07 at 04:39
Thanks a bunch – that’s really cool!
Mike at 14 Nov 07 at 00:47
Absolutely spot on! Exactly what I needed for a current project. Thanks!
Jon Sidnell at 01 Dec 07 at 09:47
Mike Tunnicliffe at 09 Dec 07 at 19:31
Just wanted to say thanks… this is a handy snippet!
Dan Sweeney at 05 Apr 08 at 14:10
Holy crap! You’re a genius! Awesome man.
Michael Madison at 12 May 08 at 02:24
nice post! and thanks Mike Tunnicliffe, your additional bit was very helpful :)
barron logan at 01 Dec 08 at 10:51
spankingly good
todd at 31 Dec 08 at 01:43
Very useful
AntonioX at 21 Jul 09 at 14:25
Perfect. Works like a charm. Thanks a bunch. The internet is such a great reference manual with posts like this.
MikeL at 23 Jul 09 at 08:35
Thanks for taking the time to post this. Simple, efficient and works.
Jim Kath at 22 Sep 09 at 16:32
Articles Archive →
Got something to say?