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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | # application controller def find_layout(params, default = nil) default ||= controller_name layout 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:
1 2 3 4 5 6 | 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.
Related posts: