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 Rails developer for Kyan web agency.
Checkout his ramblings about music, what he's listening to and his other random thoughts.
He also writes on the Kyan blog.
More snippets
Take a look in the archive
Need a website?
Your best bet is to contact Paul's employer. Make sure to check out the portfolio of work.
Hosting
I recommend hostingrails.com
Recommended Reading
Contact
my name at gmail.com
9 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!
This approach looks superior to what I found in the Rails docs, which was to use:
bq. layout :default_layout
def some_action
render :action => “some_action”, :layout => “different_layout”
end
Just wanted to say thanks… this is a handy snippet!
Holy crap! You’re a genius! Awesome man.
nice post!
and thanks Mike Tunnicliffe, your additional bit was very helpful
:)
spankingly good
Got something to say?