Rails conditional ('if') statements based on controller action

后端 未结 4 1240
别跟我提以往
别跟我提以往 2021-01-31 16:59

There might be a better way to do this, but I\'m trying to make an if statement in rails, based on the current action, in a controller (this will be used in a view).

For

相关标签:
4条回答
  • 2021-01-31 17:36

    It's not good practice IMO to have partials asking what the current controller and action names are. Think "tell, don't ask" (http://www.pragprog.com/articles/tell-dont-ask). That is, rather than having the partial ask it's caller about its state, tell the partial what you want it to do.

    One way to do this is by passing variables to the partial through the locals option:

    <%= render :partial => "/common/toolbar", :locals => {:edit => true} %>
    

    Then in the partial:

    <% if defined?(edit) && edit %>
    ... stuff appropriate to edit mode
    <% end %>
    
    0 讨论(0)
  • 2021-01-31 17:48

    The params hash that is available in the controller contains :controller and :action keys, which specify the controller and action names of the request.

    Therefore you could say

    if params[:action] == "foo"
      # Show stuff for action 'foo'
    elsif params[:action] == "bar"
      # Show stuff for action 'bar'
    elsif ...
      # etc.
    end
    
    0 讨论(0)
  • 2021-01-31 17:54

    You can use layouts for partials too:

    <%= render :partial => 'some_partial', :layout => 'wrap_with_stuff' %>
    

    If you want to work out what layout to use dynamically I'd put that in a helper. So you'd end up with

    # In your view
    
    <%= render :partial => 'some_partial', :layout => layout_for_my_partial %>
    
    # In your helper
    
    def layout_for_my_partial
        params[:action] == 'show' ? 'show_wrapper' : 'everything_else_wrapper'
    end
    

    This will only work in some circumstances, but might be what you're trying to do.

    See more here.

    http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts

    0 讨论(0)
  • 2021-01-31 18:00

    You can do it this way:

    class ApplicationController < ActionController::Base
      layout :set_layout
    
      def set_layout
        case params[:action]
        when "foo"
          "foo_layout"
        when "bar"
          "bar_layout"
        ...
        else
          "default_layout"
        end
      end
    
      ...
    
    end
    

    hope it helps =)

    0 讨论(0)
提交回复
热议问题