Nifty RubyOnRails Layout Method
So I find myself in many situations where different actions need different layouts, which is common in large multiuser systems. For example, in my system, when you are viewing a user index, it loads the layout ‘application’. When you’re viewing the edit action, it loads the layout ‘profile’, otherwise it loads the layout ‘user’. I hacked up a tiny method to toss in the application controller:
-
# application controller
-
def find_layout(params, default = nil)
-
default ||= controller_name
-
params[action_name.to_sym] || default
-
end
-
-
# user controller
-
before_filter do |c|
-
c.find_layout({
-
:edit => ‘profile’,
-
:index => ‘application’
-
})
-
end
As you can see, you simply pass a hash to the find_layout method with the actions and the layout to use. You can optionally do:
-
before_filter do |c|
-
c.find_layout({
-
:edit => ‘profile’,
-
:index => ‘application’
-
}, ’some_other_default_layout’)
-
end
This will make the default layout ’some_other_default_layout’. I know this could probably be improved in many ways, but it’s simple, it works, and that’s what I like.
Trackbacks
Use this link to trackback from your own site.