Rails - 带有 data-* 属性的 link_to 助手 [英] Rails - link_to helper with data-* attribute
问题描述
可能的重复:
使用 html5 数据属性的最佳方式rails content_tag 助手?
如何在我的 link_to 助手(Rails)中使用 html5 data-*
属性
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
例如:
link_to "whatever", @whatever_path, { class: 'my_class', data-tooltip: 'what I want' }
推荐答案
只需将它们传入... Rails 有一个默认的 :data
哈希
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' }
或者你也可以直接写:
= 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 is now the preferred formatting:
{ data: { foo: "bar" } }
这篇关于Rails - 带有 data-* 属性的 link_to 助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!