Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding dynamic attributes to HAML tag using helper method in rails

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
like image 269
Pål Avatar asked Dec 26 '22 23:12

Pål


2 Answers

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.

like image 123
Mik Avatar answered Mar 01 '23 23:03

Mik


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

like image 22
hoffmanc Avatar answered Mar 01 '23 22:03

hoffmanc