Html Rails - 带有 data-* 属性的 link_to 助手
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8734722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails - link_to helper with data-* attribute
提问by eveevans
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)
如何data-*
在我的 link_to 助手(Rails)中使用 html5 attrubute
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
API 说我必须使用这种格式,link_to(body, url, html_options = {})
但是当我将它放入 html_options 时出现错误
Ex:
前任:
link_to "whatever", @whatever_path, { class: 'my_class', data-tooltip: 'what I want' }
回答by sethvargo
Just pass them in... Rails has a default :data
hash
只需将它们传入... Rails 有一个默认的:data
哈希值
= 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:
更新:在 Rails 4 中,下划线会自动转换为破折号,因此您可以这样做:
: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 some believe is cleaner:
更新 2:正如评论中所指出的,Ruby 1.9+ 允许这种语法,有些人认为它更清晰:
{ data: { foo: "bar" } }
回答by Robin
Add a data-
attribute by doing the following:
data-
通过执行以下操作添加属性:
link_to "Hello", hello_path, :"data-attribute" => "yeah!"