在Rails中使用helper方法将动态属性添加到HAML标签

问题描述:

所以我想出了一种方法,但是有一种更简单的方法吗? 我想做的就是如果params [:sort] == sortBy,在%th标记后添加.class,我真的需要在辅助方法中保留其余的HAML吗?

So i figured out a way of doing this, but is there an easier way to do it? What i want to do is just to add .class after the %th tag if params[:sort] == sortBy, do i really need to have the rest of the HAML in the helper-method?

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

This is my helper method from my helper.rb file:

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

这来自我的HAML文件:

This is from my HAML file:

%tr
  - yellow?("title","Movie Title","title_header")
  %th Rating

您是否尝试过此解决方案:

Have you tried this solution:

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

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

You can move this statement: if params[:sort] == 'sortBy' then 'hilite' end to a helper. Take a look to my similar answer: haml two spaces issue.