Friday, April 15, 2011

More than one layout for a controller

Is it possible to do something like this:

class SimulationController < ApplicationController
  layout "generic", :only => [:login, :invalid]
  layout "menubar", :except => [:login, :invalid]

For some reason, my login page still uses the menubar layout (I can tell because a menu bar will appear at the top). If I comment out the 3rd line, the menu bar will disappear. So it seems like both layouts are being applied one after another.

But if I comment out the layout "generic"bit, I will it will be just black and white, meaning no CSS style sheet is applied.

From stackoverflow
  • One way to do this is actually within your actions.

    def login
      render :action => "login", :layout => "generic"
    end
    

    You could also make the actual "menubar" html a partial and turn the rendering off under certain conditions.

  • You look like you're trying to apply different layouts under different run-time conditions. The simplest way to tackle this is using a method reference for the layout.

    For example: -

    class ResourceController < ActionController::Base
      layout :choose_layout
    
      private
        def choose_layout    
          if [ 'signup', 'login' ].include? action_name
            'login_layout'
          else
            'admin_layout'
          end
        end
    

    Check out the Rails API reference for ActionController::Layout under the heading "Types of Layout"

  • Take a look at this ticket, your problem seems to be similar: [http://dev.rubyonrails.org/ticket/8867]

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.