Adding dynamic attributes to HAML tag using helper method in rails

北慕城南 提交于 2019-12-01 05:10:34

问题


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?

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

This is from my HAML file:

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

回答1:


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

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.




回答2:


You can also do it this way:

app/helpers/some_helper.rb

def hilite
  params[:sort] == 'sortBy' ? { class: 'hilite' } : {}
end

app/views/some.html.haml

%tr
  %th{ hilite }
    = link_to "Movie Title", movies_path(:sort => 'title'), :id => "title_header"
  %th Rating

I used this approach to make a span_field_opts helper, to mimic a disabled field via Bootstrap classes:

def span_field_opts
  { class: "form-control cursor-none", disabled: true }
end

Reference: https://coderwall.com/p/_jiytg/conditional-html-tag-attribute-in-haml



来源:https://stackoverflow.com/questions/10902377/adding-dynamic-attributes-to-haml-tag-using-helper-method-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!