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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With