默认情况下如何在输入字段中获取class ="form-control"(Rails Form Helper + Bootstrap 3)

wir*_*din 6 ruby-on-rails twitter-bootstrap twitter-bootstrap-3

我正在将我的网站转换为Twitter Bootstrap 3,并且遇到了似乎很愚蠢的问题,但我还没能通过谷歌找到一个简单的解决方案.

如何在Rails Form Helper中默认填充class ="form-control"?我只能通过明确输入来实现,这似乎是浪费时间.(下面)

引导程序需要为输入设置样式.

 <%= f.label :email %>                                     
 <%= f.text_field :email, class: "form-control" %>   
Run Code Online (Sandbox Code Playgroud)

我是否天真地认为Rails应该添加此功能只是因为bootstrap实现了它?

Ros*_*len 10

是的,这可以在不改变你使用Rails表单助手的方式的情况下完成.如果表单助手尚未包含在选项中,则可以扩展表单助手以包含类名称.

Note: You will have to override each method in FormTagHelper that you want to augment. This only augments text_field_tag.

Add something like this to your ApplicationHelper:

module ApplicationHelper

  module BootstrapExtension
    FORM_CONTROL_CLASS = "form-control"

    # Override the 'text_field_tag' method defined in FormTagHelper[1]
    #
    # [1] https://github.com/rails/rails/blob/master/actionview/lib/action_view/helpers/form_tag_helper.rb
    def text_field_tag(name, value = nil, options = {})
      class_name = options[:class]
      if class_name.nil?
        # Add 'form-control' as the only class if no class was provided
        options[:class] = FORM_CONTROL_CLASS
      else
        # Add ' form-control' to the class if it doesn't already exist
        options[:class] << " #{FORM_CONTROL_CLASS}" if
          " #{class_name} ".index(" #{FORM_CONTROL_CLASS} ").nil?
      end

      # Call the original 'text_field_tag' method to do the real work
      super
    end
  end

  # Add the modified method to ApplicationHelper
  include BootstrapExtension

end
Run Code Online (Sandbox Code Playgroud)