我们想在simple_form中使用bootstrap span6。这是我们现在正在做的事情:
<%= simple_form_for(@customer, :html => {:class => 'form-horizontal'}) do |f| %>
<%= f.input :name, :label => t('CompanyName:'), :input_html => { :class => "span6" } %>
<%= f.button :submit, t('Save') , :class => BUTTONS_CLS['action'] %>
<% end %>
问题是我们需要在每个f.input中添加:input_html => {:class =>'span6'},并且我们的rails应用程序中有很多simple_forms。有没有一种方法可以分配一次span6并将其应用于应用程序中的所有简单表单?或者我们必须一步一步地将input_html => {}添加到每个f.input中。
最佳答案
the other answer中提到的config.input_class
选项是在2.1.0版本发布之后引入的。这就是为什么您会得到一个错误。使用Github的最新gem版本可以解决此问题,但是此版本需要Rails 4。
您可以通过将以下内容附加到config/initializers/simple_form.rb
来覆盖默认行为:
%w(StringInput RangeInput CollectionSelectInput GroupedCollectionSelectInput PasswordInput TextInput NumericInput).each do |class_name|
old_class = "SimpleForm::Inputs::#{class_name}".constantize
new_class = Class.new(old_class) do
def input_html_classes
super.push('span6')
end
end
Object.const_set(class_name, new_class)
end
代码说明:为了避免七次编写几乎相同的代码,我使用了一些元编程。因此,此代码执行以下操作:
它遍历代表各种类型字段的类名称数组。
接下来,它使用ActiveSupport提供的
String#constantize
方法按名称获取类。接下来,它使用
Class#new
动态创建一个类(传递给Class#new
的参数是祖先类),并在其中定义input_html_classes
方法。接下来,它为新创建的类分配名称。
最后,我们有七个覆盖了
StringInput
方法的类RangeInput
,input_html_classes
等。