使用rails中的helper方法向HAML标记添加动态属性
所以我想出了一种方法,但是有更简单的方法吗? 我想要做的只是在%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
这来自我的HAML文件:
%tr - yellow?("title","Movie Title","title_header") %th Rating
你试过这个解决方案吗?
%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两个空格问题 。
你也可以这样做:
应用程序/佣工/ some_helper.rb
def hilite params[:sort] == 'sortBy' ? { class: 'hilite' } : {} end
应用/视图/ some.html.haml
%tr %th{ hilite } = link_to "Movie Title", movies_path(:sort => 'title'), :id => "title_header" %th Rating
我使用这种方法来创建一个span_field_opts帮助器,通过Bootstrap类模仿一个禁用的字段:
def span_field_opts { class: "form-control cursor-none", disabled: true } end
参考: https : //coderwall.com/p/_jiytg/conditional-html-tag-attribute-in-haml