问题描述
如何在我的link_to帮助程序(Rails)中使用html5 数据 - *
attrubute
How can I use html5 data-*
attrubute in my link_to helper (Rails)
API说我必须使用这种格式 link_to(body,url,html_options = {})
但我在我把它放在html_options中
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' }
推荐答案
只需将它们传入... Rails有一个默认的:data
hash
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' }
更新:在Rails 4中,下划线会自动转换破折号,所以你可以这样做:
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'
更新2:正如评论中指出的,Ruby 1.9+允许这种语法,有些人认为它更清洁:
Update 2: As pointed out in the comments, Ruby 1.9+ allows this syntax, which some believe is cleaner:
{ data: { foo: "bar" } }
这篇关于Rails - link_to helper与data- *属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!