如何使用 Bootstrap 5 和 simple_form 编写切换开关

How do you write a toggle switch with Bootstrap 5 and simple_form

https://getbootstrap.com/docs/5.0/forms/checks-radios/#switches。切换开关是格式化布尔复选框的另一种方式。

<%= simple_form_for(@location) do |form| %>
  <%= form.input :pre1890 %>

生成默认复选框。 I'd like a toggle switch or maybe a labeled button.

我想我已经看到 JavaScript pre Bootstrap 5 的解决方案,但如果需要 JavaScript,我将使用默认设置。谢谢。

config/initializers/simple_form.rb

中添加此配置
  config.wrappers :bootstrap_toggle, tag: 'div', class: 'form-check form-switch', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b|
    b.use :html5
    b.optional :readonly
    b.use :label, class: 'form-check-label'
    b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
    b.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' }
    b.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' }
  end

并将其配置为布尔值

config.wrapper_mappings = {
  boolean:       :bootstrap_toggle,
  # ....
}

注意:如果您将 bootstrap 与简单格式一起使用,请检查此 https://github.com/heartcombo/simple_form#bootstrap

或参考此代码

  config.wrappers :vertical_boolean, tag: 'fieldset', class: 'form-group', error_class: 'form-group-invalid', valid_class: 'form-group-valid' do |b|
    b.use :html5
    b.optional :readonly
    b.wrapper :form_check_wrapper, tag: 'div', class: 'form-check' do |bb|
      bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid'
      bb.use :label, class: 'form-check-label'
      bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' }
      bb.use :hint, wrap_with: { tag: 'small', class: 'form-text text-muted' }
    end
  end

https://github.com/heartcombo/simple_form/blob/123d3b3822cb8a23c6216261f32d5e1af139a087/lib/generators/simple_form/templates/config/initializers/simple_form_bootstrap.rb#L66