Adding dynamic attributes to HAML tag using helper method in rails

冷暖自知 提交于 2019-12-01 06:54:07
Mik

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.

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

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