我正在使用datepicker并想要创建自定义的simple_form输入
目前我在每个表格上这样做:
<link rel="stylesheet" href="/datepicker/master/dist/datepicker.min.css">
<script src="/datepicker/master/dist/datepicker.min.js"></script>
<%= simple_form_for(myobj) do |f| %>
<%= f.input :some_date, as: :string, input_html: {class: "datepicker", onchange: "this.form.submit();", autocomplete: "off"} %>
<% end %>
<script>
$(function() {
$(".datepicker").datepicker({format: "yyyy-mm-dd"});
});
</script>
这在第一次之后变得烦人,所以我创建了一个自定义输入:
# app/inputs/datepicker_input.rb
class DatepickerInput < SimpleForm::Inputs::Base
def input(wrapper_options={})
wrapper_options.symbolize_keys!
wrapper_options[:input_html] ||= {class: 'datepicker', onchange: 'this.form.submit();', autocomplete: 'off'}
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
template.content_for(:head) do
[
template.stylesheet_link_tag('https://rawgit.com/fengyuanchen/datepicker/master/dist/datepicker.min.css'),
template.javascript_include_tag('https://rawgit.com/fengyuanchen/datepicker/master/dist/datepicker.min.js')
].join.html_safe
end
js = <<JS
<script type="text/javascript">
$(function() {$(".datepicker").datepicker({format: "yyyy-mm-dd"});});
</script>
JS
template.content_for(:javascript) { js.html_safe }
@builder.text_field(attribute_name, merged_input_options).html_safe
end
end
这让我做:
<%= simple_form_for(myobj) do |f| %>
<%= f.input :some_date, as: :my_datepicker %>
<% end %>
不幸的是,它多次包括JS / CSS,并没有找到一个可靠的解决方案来防止它。
# app/inputs/datepicker_input.rb
class DatepickerInput < SimpleForm::Inputs::Base
def input(wrapper_options={})
wrapper_options.symbolize_keys!
wrapper_options[:input_html] ||= {class: 'datepicker', onchange: 'this.form.submit();', autocomplete: 'off'}
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
unless template.instance_variable_get(:@submitted_content_for_head)
# prevents from being inserted twice
template.instance_variable_set(:@submitted_content_for_head, true)
template.content_for(:head) do
[
template.stylesheet_link_tag('https://rawgit.com/fengyuanchen/datepicker/master/dist/datepicker.min.css'),
template.javascript_include_tag('https://rawgit.com/fengyuanchen/datepicker/master/dist/datepicker.min.js')
].join.html_safe
end
end
unless template.instance_variable_get(:@submitted_content_for_footer)
# prevents from being inserted twice
template.instance_variable_set(:@submitted_content_for_footer, true)
js = <<JS
<script type="text/javascript">
$(function() {$(".datepicker").datepicker({format: "yyyy-mm-dd"});});
</script>
JS
template.content_for(:javascript) { js.html_safe }
end
@builder.text_field(attribute_name, merged_input_options).html_safe
end
end
我只是简单地在主模板中移动CSS / JS文件以及JavaScript代码段,而不用担心通过自定义输入添加它们。甚至将它们编译成主要的CSS和JS文件,以避免额外的页面加载调用。