使用rails中的helper方法向HAML标记添加动态属性

Pål*_*Pål 4 haml ruby-on-rails

所以我想出了一种方法,但是有更简单的方法吗?我想要做的只是在%th标签之后添加.class如果params [:sort] == sortBy,我真的需要在helper方法中使用其余的HAML吗?

这是我的helper.rb文件的助手方法:

def yellow?(sortBy,name,id)
  haml_tag :th, class: "#{'hilite' if params[:sort]== sortBy}" do
    haml_concat link_to name, movies_path(sort: sortBy),{:id => id}
  end
end
Run Code Online (Sandbox Code Playgroud)

这来自我的HAML文件:

%tr
  - yellow?("title","Movie Title","title_header")
  %th Rating
Run Code Online (Sandbox Code Playgroud)

Mik*_*Mik 8

你试过这个解决方案吗?

%tr
  %th{ :class => if params[:sort] == 'sortBy' then 'hilite' end }
    = link_to "Movie Title", movies_path(:sort => 'title'), :id => "title_header"
  %th Rating
Run Code Online (Sandbox Code Playgroud)

您可以将此语句移动if params[:sort] == 'sortBy' then 'hilite' end到帮助程序.看看我的类似答案:haml两个空格问题.