如何将HTML5自动焦点添加到rails表单?

我有一个文本字段

= text_field_tag('search_text_1', params[:search_text], options = {:type => 'search'} ) 

产生

  

我想要添加HTML5自动对焦,如

  = text_field_tag('search_text_1', params[:search_text], options = {:type => 'search', :autofocus => true} ) 

这会产生

  

哪个确实有效,但我怎么能得到autofocus的实际HTML输出,就像HTML规范所示,即

  # Not sure where it goes or if that matters 

运用

 options = {:type => 'search', :autofocus } 

 .../_search.html.haml:2: syntax error, unexpected '}', expecting => ...:type => 'search', :autofocus } ) 

正如https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input上的HTML5规范所说,“这是一个布尔”

如果您愿意修补私有Rails方法,则可以实现所需的输出。 Rails使用TagHelper模块中的boolean_tag_option方法写出布尔属性,该模块生成autofocus='autofocus'格式。

如果将以下内容添加到初始值设定项,则可以将此方法替换为以最小化格式写出属性的方法。

 module ActionView::Helpers::TagHelper private def boolean_tag_option(key) key end end 

显然,升级您的应用程序使用的Rails版本时需要小心。 这个方法目前看起来相当稳定,它仍然存在于4.2.0.beta.1和master中 。

我结束了

 = text_field_tag('search_text_1', params[:search_text], options = {:type => 'search', :autofocus => true }) 

并接受autofocus='autofocus'的输出