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!"
Share:
72,588

Related videos on Youtube

eveevans
Author by

eveevans

Developer

Updated on December 14, 2020

Comments

  • eveevans
    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_options

    Ex:

    link_to "whatever", @whatever_path, { class: 'my_class', data-tooltip: 'what I want' }
    
    • Frederick Cheung
      Frederick Cheung over 12 years
      what does your current attempt look like?
  • eveevans
    eveevans over 12 years
    It works perfectly, May I ask => where did you notice of that :data syntax?
  • sethvargo
    sethvargo over 12 years
    I 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
    Ashitaka almost 12 years
    I'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
    John over 11 years
    For 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
    Admin over 10 years
    data: { foo: {bar: 'that' }
  • stephencelis
    stephencelis over 10 years
    The gotcha is actually that underscored entities are dasherized automatically. :data => { :foo_bar => 'that' } becomes data-foo-bar="that". No need to quote the symbols.