simple_form中的包装器映射

ard*_*igh 6 ruby-on-rails simple-form

在github上的simple_form示例repo中,有一个包含包装器信息的块. https://github.com/rafaelfranca/simple_form-b​​ootstrap/blob/master/app/views/examples/_horizo​​ntal_form_sf.html.erb

它工作正常,但似乎需要为每个表单添加许多额外的设置.有没有办法添加名称此信息并将其添加为参数?

<%= simple_form_for @user_horizontal, url: create_horizontal_examples_url, as:     'user_horizontal', html: { class: 'form-horizontal' },
  wrapper: :horizontal_form,
  wrapper_mappings: {
    check_boxes: :horizontal_radio_and_checkboxes,
    radio_buttons: :horizontal_radio_and_checkboxes,
    file: :horizontal_file_input,
    boolean: :horizontal_boolean
  } do |f| %>
  <%= f.error_notification %>
  <%= f.input :email, placeholder: 'Email' %>
Run Code Online (Sandbox Code Playgroud)

Mau*_*res 15

在视图帮助器中,添加:

def wrapped_form(resource, options = {}, &block)
  options[:html] = { class: 'form-horizontal'}
  options[:wrapper] = :horizontal_form
  options[:wrapper_mappings] = {
    check_boxes: :horizontal_radio_and_checkboxes,
    radio_buttons: :horizontal_radio_and_checkboxes,
    file: :horizontal_file_input,
    boolean: :horizontal_boolean
  }
  simple_form_for(resource, options, &block)
end
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用:

<%= wrapped_form @user_horizontal, url: create_horizontal_examples_url, as: 'user_horizontal' do |f| %>
  <%= f.error_notification %>
  <%= f.input :email, placeholder: 'Email' %>
<% end %>
Run Code Online (Sandbox Code Playgroud)

  • 我宁愿做这样的事情:options [:html] || = {}; options [:html] [:class] ='form-vertical'所以我不会覆盖传递的HTML选项(如果有的话).否则,这很棒. (2认同)