【问题标题】:simple_form custom input with custom wrapper带有自定义包装器的 simple_form 自定义输入
【发布时间】:2013-03-14 04:25:53
【问题描述】:

我正在尝试在我的应用中为货币进行自定义输入。我有那些引导包装器等(我认为它带有 simple_form 或引导 gem ......),所以,我可以做类似的事情:

<%= f.input :cost, wrapper => :append do %>
      <%= content_tag :span, "$", class: "add-on" %>
      <%= f.number_field :cost %>
<% end %>

而且它按预期工作。问题是:我在很多地方都需要同样的东西,我不想到处复制/粘贴。

所以,我决定创建一个自定义输入。

到目前为止,我得到了以下代码:

class CurrencyInput < SimpleForm::Inputs::Base

  def input
    input_html_classes.unshift("string currency")
    input_html_options[:type] ||= input_type if html5?

    @builder.input attribute_name, :wrapper => :append do |b|
      # content_tag(:span, "$", class: "add-on")
      b.text_field(attribute_name, input_html_options)
    end
  end
end

但是我遇到了一些错误。看起来b 没有按预期出现,所以它只是不起作用。

真的可以做到吗?我找不到任何示例,也无法自己完成。

提前致谢。

【问题讨论】:

标签: ruby-on-rails simple-form


【解决方案1】:

那个块变量不存在,你的输入法必须是这样的:

class CurrencyInput < SimpleForm::Inputs::Base

  def input
    input_html_classes.unshift("string currency")
    input_html_options[:type] ||= input_type if html5?

    template.content_tag(:span, "$", class: "add-on") +
      @builder.text_field(attribute_name, input_html_options)
  end
end

现在您可以在 Simple Form 初始化程序中为这个自定义输入注册一个默认包装器:

config.wrapper_mappings = { :currency => :append }

你可以这样使用:

<%= f.input :cost, :as => :currency %>

【讨论】:

  • 就是这样!非常感谢 Rafael,我不知道按字段类型设置的包装器。干杯!
猜你喜欢
  • 2014-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多