October 15, 2006

Posted by John

Tagged layouts

Older: Rails Gets Unicode Handling

Newer: Building A Multi-Site Application

Action Based Layouts

In an app I’m working on right now, I wanted to change the layout for the entire application based on the action name. I’ve seen a few ways to do this but here is what I put in application.rb:

layout proc{ |c| ['show', 'new', 'edit'].include?(c.action_name) ? 'single_column' : 'application' }

Now, the show, new and edit actions will render with the ‘single_column’ layout and the rest will render with the ‘application’ layout.

I saw someone put this in a post:

layout 'single_column', :only => [:show, :new, :edit]
layout 'application', :except => [:show, :new, :edit]

But it didn’t work for me. If anyone knows how to get something along those lines working, let me know and I’ll update this tip. Above is not the only way to change the layout based on the action. You can also:

layout :decide_template

protected
def decide_template
  if ['show', 'new', 'edit'].include?(action_name)
    'single_column'
  else
    'application'
  end
end

Which allows for more complex decisions if needed.

0 Comments

Sorry, comments are closed for this article to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a programmer who has fallen deeply in love with Ruby. Learn More.

Projects

Flipper
Release your software more often with fewer problems.
Flip your features.