Ruby-on-rails 自定义 HTML 属性需要自定义助手?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5200260/
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
Custom HTML attribute requires a custom helper?
提问by RSG
I'm trying to create a form with some custom data attributes on the inputs:
我正在尝试在输入上创建一个带有一些自定义数据属性的表单:
<input type="text" data-family="Dinosaurs">
This seemed like a nice clean way to have easy front-end access (haha!) with jquery:
这似乎是一种使用 jquery 轻松访问前端(哈哈!)的好方法:
$("[data-family='Dinosaurs']").doSomething()
The problem is I can't get Rails (3.0.3) to render the attribute.
问题是我无法让 Rails (3.0.3) 来呈现属性。
<%= f.text_field :question, :id=>"poll_question", :class=>"BigInput", :style=>"width:98%;", :attributes=>"data-submit_clear='1'" %>
I've tried many permutations to no avail and can't find an example of how to do this. Do I need to modify the text_fieldhelper to support any custom attributes?
我尝试了很多排列都无济于事,也找不到如何做到这一点的例子。我是否需要修改text_field帮助程序以支持任何自定义属性?
回答by RSG
Oops. It's just
哎呀。只是
<%= f.text_field :question, :id=>"poll_question", :class=>"BigInput", :style=>"width:98%;", 'data-submit_clear'=>'1' %>
回答by Steve Grossi
Rails >3.1 has a handy shortcut for data-attributes like this which most HTML-generating helpers support:
Rails >3.1 有一个方便的快捷方式来处理大多数 HTML 生成助手支持的数据属性:
<%= f.text_field :question, :data => { :submit_clear => '1' } %>
It can make things more readable when you have a couple of data attributes, e.g.:
当您有几个数据属性时,它可以使事情更具可读性,例如:
<%= f.text_field :question, :data => { :submit_clear => '1', :more_info => 'Ok', :also => 'this' } %>

