Thursday, August 4, 2011

Rails' link_to: specifying miscellaneous attributes

If you ever need to specify miscellaneous attributes, as I did when making my Rails 3.1 app mobile with jQuery Mobile, there's an easy way to do it.

Example: I want to create a link with the following...
<a href="" data-direction="reverse" data-rel="back" data-prefetch>xyz</a>

Just do this (in your embedded ruby html file):
<%= link_to "xyz", my_path, "data-direction"=>"reverse", "data-rel"=>"back", "data-prefetch"=>"" %>

The order of the variables after the path specification (my_path, in this case) generally does not matter, so you could put :class => "my_class" before, in the middle, or after those "data-" parameters too, and you could rearrange the "data-" parameters however you like.
Also, note the specification of "data-prefetch"=>"" in the case that there is no attribute to set equal to.

This whole idea came especially in handy for me because jQuery mobile uses such things frequently. However, the idea of specifying
"some_variable"=>"some_value"
in the link_to method can be applied to broader scenarios, too; it just might help you out.

1 comment:

Please be considerate in what you say.