簡體   English   中英

您如何使用 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 撥動開關是另一種格式化 boolean 復選框的方式。

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

產生一個默認復選框。 默認截圖 我想要一個撥動開關或者一個帶標簽的按鈕。 從 Bootstrap 網站切換

我想我已經看到了用於預引導 5 的 JavaScript 解決方案,但如果需要 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

並將其配置為 boolean

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

注意:如果您使用帶有 simpleform 的引導程序,請檢查此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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM