Nifty RubyOnRails Layout Method

Posted by kris on August 01, 2008

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:

Code: ruby
  1. # application controller
  2. def find_layout(params, default = nil)
  3.   default ||= controller_name
  4.   params[action_name.to_sym] || default
  5. end
  6.  
  7. # user controller
  8. before_filter do |c|
  9.   c.find_layout({
  10.     :edit => ‘profile’,
  11.     :index => ‘application’
  12.   })
  13. 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:

Code: ruby
  1. before_filter do |c|
  2.   c.find_layout({
  3.     :edit => ‘profile’,
  4.     :index => ‘application’
  5.   }, ’some_other_default_layout’)
  6. 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.

Comments

Leave a response

Comments

Close
E-mail It