如何为Simple Form的布尔输入字段定义不同样式类?
解决Simple Form布尔字段样式隔离问题
方案一:为布尔字段单独定义包装器
在初始化器中保留原有默认包装器,新增布尔字段专属包装器后,指定布尔字段使用新规则:
# 保留原有的默认包装器(仅作用于非布尔字段) config.wrappers :default, tag: "div", class: "my-form-group", error_class: "has-error" do |b| b.use :html5 b.use :placeholder b.use :label, class: "my-label" b.use :input, class: "my-input" b.use :error, wrap_with: { tag: "span", class: "help-inline" } b.use :hint, wrap_with: { tag: "p", class: "help-block" } end # 新增布尔字段专属包装器,可自定义结构和样式类 config.wrappers :boolean, tag: "div", class: "my-boolean-group", error_class: "has-error" do |b| b.use :html5 b.use :placeholder b.use :label, class: "my-boolean-label" b.use :input, class: "my-boolean-input" # 这里设置布尔字段的input专属类 b.use :error, wrap_with: { tag: "span", class: "help-inline" } b.use :hint, wrap_with: { tag: "p", class: "help-block" } end # 指定布尔字段使用新包装器 config.wrapper_mappings = { boolean: :boolean }
配置完成后,普通字段仍沿用原有默认样式,布尔字段会应用你自定义的:boolean包装器规则。
方案二:在默认包装器中动态适配布尔字段
如果不想新增包装器,可通过条件判断为布尔字段单独设置样式:
config.wrappers :default, tag: "div", class: "my-form-group", error_class: "has-error" do |b| b.use :html5 b.use :placeholder b.use :label, class: "my-label" # 根据字段类型动态切换input类:布尔字段用专属类,其他字段用原类 b.use :input, class: lambda { |input| input.type == :boolean ? "my-boolean-input" : "my-input" } b.use :error, wrap_with: { tag: "span", class: "help-inline" } b.use :hint, wrap_with: { tag: "p", class: "help-block" } end
这种方式无需新增包装器,仅通过动态判断就能实现布尔字段的样式隔离。
内容的提问来源于stack exchange,提问作者ReggieB
相关产品推荐
相关产品推荐

