How to pass a variable to a layout?

前端 未结 5 2079
时光说笑
时光说笑 2021-02-05 14:27

I have a two versions of my application layout, which are differs only in a few lines. Consider following example:

!!!    
%html
    %head
        # a lot of cod         


        
5条回答
  •  醉话见心
    2021-02-05 15:15

    I usually prefer to use helper methods instead of instance variables in these situations. Here is an example of how it could be done:

    class ApplicationController < ActionController::Base
      layout 'layout'
      helper_method :flag
    
      ...
    
    protected
      def flag
        true
      end
    end
    

    And if you have a controller where flag should not be true then you just overwrite the method:

    class PostsController < ApplicationController
      ...
    
    private
      def flag
        false # or perhaps do some conditional
      end
    end
    

    This way you make sure that the flag helper is always available in views so you don't have to do the if defined? or anything and also, in the cases where no layout is used, then no instance variable is assigned in any before_filter.

    It also helps keep as few instance variables as possible in the views.

提交回复
热议问题