Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 202
evanx Avatar asked Feb 02 '13 02:02

evanx


2 Answers

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>
like image 167
Chris Salzberg Avatar answered Nov 01 '22 11:11

Chris Salzberg


To add an id selector in haml using link_to you have to specify two hashes.

e.g = link_to "Link 1", {booking_path, extra arg...}, {:id => 'booked'}

An important Ruby idiom is poetry mode: the ability to omit parentheses and curly braces when the parsing is unambiguous. Most commonly, Ruby programmers may omit parentheses around arguments to a method call, and omit curly braces when the last argument to a method call is a hash. Hence the following two method calls are equivalent, given a method link_to that takes one string argument and one hash argument:

Without curly braces, there’s no way to tell whether this call is trying to pass a hash with two keys or two hashes of one key each. Therefore poetry mode can only be used when there’s a single hash argument and it’s the last argument.

Patterson, David; Fox, Armando (2012-08-24). Engineering Long-Lasting Software: An Agile Approach Using SaaS and Cloud Computing, Beta Edition (Kindle Locations 1973-1975). Strawberry Canyon LLC. Kindle Edition.

like image 44
evanx Avatar answered Nov 01 '22 12:11

evanx