Rails and haml, how to add id and class selectors to link_to helper?

evanx picture evanx · Feb 2, 2013 · Viewed 28.2k times · Source

I've been looking around how to add an id selector to a link_to helper using haml, is that possible?

  a .haml - %a#booked{:href => "index.haml"} Link 1    

  b .html.erb - booking.html.erb - <%= link_to "Link 1", booking_path, :id => "booked" %>

  c .haml.erb - booking.haml.erb - ...??

Which would be the equivalent of b in haml?

Answer

Chris Salzberg picture Chris Salzberg · Feb 2, 2013

link_to works exactly the same way in haml as it does in erb. So this will do what you want:

= link_to "Link 1", booking_path, :id => "booked"
#=> <a id="booked" href="/bookings">Link 1</a>

You can also assign a class attribute in this way:

= link_to "Link 1", booking_path, :id => "booked", :class => "some_class"
#=> <a id="booked" class="some_class" href="/bookings">Link 1</a>

More on how to insert ruby code in haml: Inserting ruby

And, just so there are no doubts about passing ids and classes to link_to, here is an example from the docs:

link_to "Articles", articles_path, :id => "news", :class => "article"
#=> <a href="/articles" class="article" id="news">Articles</a>