Rails set layout from within a before_filter method

前端 未结 3 1132
闹比i
闹比i 2020-12-31 01:34

Is it possible to reset a default layout from within a before_filter method in Rails 3?

I have the following as my contacts_controller.rb:

cla         


        
相关标签:
3条回答
  • 2020-12-31 01:53

    From Rails guides, 2.2.13.2 Choosing Layouts at Runtime:

    class ProductsController < ApplicationController
      layout :products_layout
    
      private
    
      def products_layout
        @current_user.special? ? "special" : "products"
      end
    end
    
    0 讨论(0)
  • 2020-12-31 02:08

    If for some reason you cannot modify the existing controller and/or just want to do this in a before filter you can use self.class.layout :special here is an example:

    class ProductsController < ApplicationController
      layout :products
      before_filter :set_special_layout
    
      private
    
      def set_special_layout
        self.class.layout :special if @current_user.special?
      end
    end
    

    It's just another way to do essential the same thing. More options make for happier programmers!!

    0 讨论(0)
  • 2020-12-31 02:15

    The modern way of doing this is to use a proc,

    layout proc { |controller| user.logged_in? "layout1" : "layout2" }
    
    0 讨论(0)
提交回复
热议问题