Conditionally setting CSS style from ruby controller

前端 未结 5 1590
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 11:07

I\'m trying to dynamically change (if it got clicked) a normal table header (which is a link) to another defined CSS class \'th.hilite\'. This link simply sorts this column and

相关标签:
5条回答
  • 2021-02-01 11:34

    You can bind it from the view directly:

    %th{:class => ("hilite" if @sort == "title")}= link_to 'Movie Title'...

    However, you will also have to declare the @sort instance variable in your controller, and set it to either title or release, according to which column you are sorting. (i.e. @sort = params[:sort])

    0 讨论(0)
  • 2021-02-01 11:34

    BTW as long as values of your param match column name - no need to code each one

    def index
        @by=params[:by]
        @movies = Movie.order(params[:by]).all
      end
    
    0 讨论(0)
  • 2021-02-01 11:37

    Javascript or jquery is not required..

    The following HAML will work

    %th{:class=>('title' == @sortby)?'hilite':""}= link_to  'Movie Title', movies_path(:sort => 'title'), :id => 'title_header'
    
    0 讨论(0)
  • 2021-02-01 11:46

    You should use JavaScript to do this. I think it's good idea for you to use jQuery instead of pure JavaScript. Here are some examples

    http://api.jquery.com/click/

    http://api.jquery.com/css/

    0 讨论(0)
  • 2021-02-01 11:51

    Be careful not to put logic (even conditionals) in your views if you can find a way around it. In order to avoid this common mistake, you need to make good use of the params and session hashes and set appropriate variables in controllers

    # In your view
    %th{:class => @title_header}= link_to 'Title', my_path(:sort => 'title'), :id => 'title_header'
    
    # In your controller
    sort = params[:sort] || session[:sort]
    if sort == 'title'
      ordering = {:order => :title}
    end
    
    0 讨论(0)
提交回复
热议问题