2012-01-04 69 views
93

可能重複:
Best way to use html5 data attributes with rails content_tag helper?導軌 - 的link_to助手與數據 - *屬性

如何使用HTML5 data-* attrubute在我的link_to助手(Rails)的

的API說,我必須使用這種格式link_to(body, url, html_options = {}),但我有一個錯誤,當我把它放在html_options

例如:

link_to "whatever", @whatever_path, { class: 'my_class', data-tooltip: 'what I want' } 
+0

你目前的嘗試是什麼樣的? – 2012-01-04 22:05:21

回答

198

只是通過他們...... Rails有一個默認的:data哈希

= link_to body, url, :data => { :foo => 'bar', :this => 'that' } 

有一個問題 - 如果包含短劃線,則必須用引號括住符號:

:data => { :'foo-bar' => 'that' } 

更新:在Rails 4,下劃線將自動轉換爲破折號,所以你可以這樣做:

:data => { :foo_bar => 'that' } 

另外,你可以只寫它直接:

= link_to body, url, :'data-foo' => 'bar', :'data-this' => 'that' 

更新2:正如在評論中指出的那樣,Ruby 1.9+允許這種語法,有些人認爲它更簡潔:

{ data: { foo: "bar" } } 
+0

它可以完美運行,請問:您在哪裏注意到:數據語法? – eveevans 2012-01-04 22:19:28

+1

我認爲這是在[Railscast](http://railscasts.com)?我不確定。我一直在使用它。它是在Rails源代碼中定義的,如果你想捅一下。 – sethvargo 2012-01-04 22:20:18

+6

我想在此爲未來的訪問者指出,使用新的Ruby 1.9語法,只有第一種方法有效。所以,你可以這樣做:data:{type:'remote'}但不是這樣:'data-type':'remote' – Ashitaka 2012-06-19 18:40:39

3

做添加data-屬性如下:

link_to "Hello", hello_path, :"data-attribute" => "yeah!"