带有自定义包装器的 simple_form 自定义输入 [英] simple_form custom input with custom wrapper
问题描述
我正在尝试在我的应用中为货币进行自定义输入.我有那些引导程序包装器等(我认为它带有 simple_form 或引导程序 gem ......),所以,我可以做这样的事情:
I'm trying to make a custom input for currency in my app. I had those bootstrap wrappers and etc (I think it comes with simple_form or with bootstrap gem...), so, I could do something like:
<%= f.input :cost, wrapper => :append do %>
<%= content_tag :span, "$", class: "add-on" %>
<%= f.number_field :cost %>
<% end %>
它按预期工作.问题是:我在很多地方都需要同样的东西,而且我不想到处复制/粘贴.
And it works just as expected. The thing is: I need this same thing in a lot of places, and I don't want to copy/paste it all around.
所以,我决定创建一个自定义输入.
So, I decided to create a custom input.
到现在为止,我得到了以下代码:
Until now, I got the following code:
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
没有按预期出现,所以,它不起作用.
But I got some errors. Looks like the b
doesn't came as expected, so, it just don't work.
真的可以这样做吗?我找不到任何示例,也无法自己让它工作.
Is it really possible to do this? I could't find any example and can't make it work by myself.
提前致谢.
推荐答案
那个块变量不存在,你的输入法必须是这样的:
That block variable is not existent, your input method have to be like this:
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
现在您可以在您的简单表单初始值设定项中为这个自定义输入注册一个默认包装器:
Now you can register a default wrapper to this custom input in you Simple Form initializer:
config.wrapper_mappings = { :currency => :append }
你可以这样使用:
<%= f.input :cost, :as => :currency %>
这篇关于带有自定义包装器的 simple_form 自定义输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!