How to specify multiple layouts within the same controller in Ruby on Rails
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.
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
7 comments made
schweet!
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.
Thanks a bunch – that’s really cool!
Absolutely spot on! Exactly what I needed for a current project. Thanks!
Just wanted to say thanks… this is a handy snippet!
Holy crap! You’re a genius! Awesome man.
Got something to say?