Rails - link_to helper with data-* attribute
72,588
Solution 1
Just pass them in... Rails has a default :data
hash
= link_to body, url, :data => { :foo => 'bar', :this => 'that' }
One gotcha - you must surround symbols with quotes if they include a dash:
:data => { :'foo-bar' => 'that' }
Update: In Rails 4, underscores are automatically converted to dashes, so you can do this:
:data => { :foo_bar => 'that' }
Alternatively you can just write it directly:
= link_to body, url, :'data-foo' => 'bar', :'data-this' => 'that'
Update 2: As pointed out in the comments, Ruby 1.9+ allows this syntax, which is now the preferred formatting:
{ data: { foo: "bar" } }
Solution 2
Add a data-
attribute by doing the following:
link_to "Hello", hello_path, :"data-attribute" => "yeah!"
Related videos on Youtube
Comments
-
eveevans over 3 years
Possible Duplicate:
Best way to use html5 data attributes with rails content_tag helper?How can I use html5
data-*
attrubute in my link_to helper (Rails)The API says that I have to use this format
link_to(body, url, html_options = {})
but I have an error when I put it in html_optionsEx:
link_to "whatever", @whatever_path, { class: 'my_class', data-tooltip: 'what I want' }
-
Frederick Cheung over 12 yearswhat does your current attempt look like?
-
-
eveevans over 12 yearsIt works perfectly, May I ask => where did you notice of that :data syntax?
-
sethvargo over 12 yearsI think it was in a Railscast? I'm not sure. I've been using it for awhile. It's defined in the Rails source if you want to poke around.
-
Ashitaka almost 12 yearsI'd like to point here for future visitors that with the new Ruby 1.9 syntax, only the first method works. So, you can do this: data: { type: 'remote' } but not this: 'data-type': 'remote'
-
John over 11 yearsFor Rails 3.0.9 specifically, you have to use the direct route with
:'data-foo'
. I might be doing something wrong, but using the:data => {}
method was putting the hash directly into the HTML. -
Admin over 10 yearsdata: { foo: {bar: 'that' }
-
stephencelis over 10 yearsThe gotcha is actually that underscored entities are dasherized automatically. :data => { :foo_bar => 'that' } becomes data-foo-bar="that". No need to quote the symbols.