想要将输入字段中的文本格式设置为货币。找到这个解决方案。
所以输入生成器看起来像这样:
def input_group(currency, merged_input_options)
"#{@builder.text_field(attribute_name, merged_input_options)} #{currency_addon(currency)}".html_safe
end
但我仍然需要强制值的十进制格式:
= f.input :price, as: :currency, input_html: { value: number_with_precision(f.object.price, precision: 2) }
是否可以改进构建器而不是可以将数字格式化为十进制本身?
谢谢
是的,这是可能的,这是一个使用 bootstrap 5 的功能齐全的示例。
使用新输入作为
f.input :price, as: :currency
放入
app/lib/simple_form/inputs/currency_input.rb
# frozen_string_literal: true
module SimpleForm
module Inputs
class CurrencyInput < SimpleForm::Inputs::Base
def input(wrapper_options)
currency = options.delete(:currency) || default_currency
wrapper_options = wrapper_options.merge(
value: number_with_precision(@builder.object.send(attribute_name) / 100.0, 2)
)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
content_tag(:div, input_group(currency, merged_input_options), class: "input-group")
end
private
def input_group(currency, merged_input_options)
"#{@builder.text_field(attribute_name, merged_input_options)} #{currency_addon(currency)} ".html_safe
end
def currency_addon(currency)
content_tag(:span, currency, class: "input-group-text")
end
def default_currency
"€"
end
end
end
end