【问题标题】:How to configure a SimpleForm input to default to no wrapper如何将 SimpleForm 输入配置为默认为无包装器
【发布时间】:2019-01-25 18:19:13
【问题描述】:

给定一个自定义的 SimpleForm 输入

class MyCustomInput < SimpleForm::Inputs::Base
  # some stuff
end

我如何配置它,以便这些输入默认没有包装器。

通常我会像这样设置特定于输入的包装器:

# initializers/simpleform
config.wrapper_mappings = {
  my_custom: :my_wrapper
}

但以下不起作用,仍然应用默认的 SimpleForm 包装器。

config.wrapper_mappings = {
  my_custom: false
}

我知道有一些方法可以在视图中实现这一点,例如,

<%= f.input :attribute, as: :my_custom, wrapper: false %>

<%= f.input_field :attribute %>

但这不是我想要的。

有没有办法配置输入以使默认没有包装器?

【问题讨论】:

    标签: ruby-on-rails simple-form


    【解决方案1】:

    除了您在问题中已经提到的选项外,仅使用 input_field 而不是 input(更多信息:https://github.com/plataformatec/simple_form#stripping-away-all-wrapper-divs),您可以像这样定义您的包装器(未经测试):

    SimpleForm.setup do |config|
      config.wrapper_mappings = {
        my_custom: :wrapper_false,
      }
    
      config.wrappers :wrapper_false, tag: false do |b|
        b.use :placeholder
        b.use :label_input
        b.use :hint,  wrap_with: { tag: :span, class: :hint }
        b.use :error, wrap_with: { tag: :span, class: :error }
      end
    end
    

    然后在你的表单中:

    <%= f.input :attribute, as: :my_custom %>
    

    有关包装 API 的更多信息:https://github.com/plataformatec/simple_form#the-wrappers-api

    编辑:

    在考虑您提到的情况后,I sent a PRsimple_form 项目允许在wrapper_mappings 中配置wrapper: false。如果它被接受,您应该能够直接在初始化程序中禁用包装器,如下所示:

    config.wrapper_mappings = {
      my_custom: false
    }
    

    【讨论】:

    • 感谢@dgilerez。这是有道理的——这意味着为“无包装器”场景创建一个自定义包装器。但是真的没有办法指定一个 wrapper_mapping 为 false 吗?
    • 从未尝试过,但深入代码我认为它不会起作用:github.com/plataformatec/simple_form/blob/master/lib/… - 如果定义了options[:wrapper_mappings][input_type]false,则不会考虑并转向其他分支if.
    • 为了支持这一点,我认为该行应该从options[:wrapper_mappings][input_type] 更改为!options[:wrapper_mappings][input_type].nil?。如果您在 repo 上打开问题,我可能会抽出时间发送 PR :P
    • 运气好@AndyHarvey?
    • 感谢@dgilperez,我使用了“无包装”包装,并且效果很好。公关工作做得很好,我期待看到 SF 尽快采用它!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多