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 the header should got highlighted every time a user sorts the list.
The view where the class in question should be changed, looks like this:
%table#mytable
%thead
%tr
%th= link_to 'Title', mytable_path(:sort => 'title'), :id => 'title_header'
My question is simply: How and where could I dynamically set the class to %th.hilite if the header is clicked?
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]
)
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
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
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With