今天做Rails百寶箱第二集
首先學(xué)的就是學(xué)選時(shí)間的UI
一般的編輯時(shí)間的代碼是:
<%= f.date_field :birthday, :class => "form-control" %>
但是這種菜單的支持的瀏覽器只有Chrome
或者用下拉的菜單:
<%= f.date_select :birthday, :class => "form-control" %>
這種下拉的菜單就沒有兼容性問題,但是就是有點(diǎn)丑,而且沒有日歷。
如果想要用漂亮的日歷,就要用gem 個(gè) bootstrap-datepicker
bootstrap-datepicker是個(gè) jQuery Plugin,并且有現(xiàn)成包好的 gem 可以直接使用bootstrap-datepicker-rails。
編輯Gemfile
Gemfile
+? gem 'bootstrap-datepicker-rails'
執(zhí)行bundle后,重啟服務(wù)器
編輯app/assets/stylesheets/application.scss
app/assets/stylesheets/application.scss
@import "bootstrap-sprockets";?
?@import "bootstrap";?
?@import "select2";? @import "select2-bootstrap";
+? @import "bootstrap-datepicker3";
編輯app/assets/javascripts/application.js
app/assets/javascripts/application.js
//= require jquery?
?//= require jquery_ujs?
?//= require turbolinks?
?//= require bootstrap-sprockets?
?//= require select2
? //= require nested_form_fields
+? //= require bootstrap-datepicker/core
+? //= require bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN//= require_tree .
編輯app/views/users/edit.html.erb,將 script 放到最下方:
app/views/users/edit.html.erb
-? <%= ff.date_field :birthday, :class => "form-control" %>
+? <%= ff.text_field :birthday, :class => "form-control" %>
# 略
+ <script>
+? ? $("#user_profile_attributes_birthday").datepicker({ format: "yyyy-mm-dd" });
+ </script>
注意格式要指定以配合 Rails,這里指定成"yyyy-mm-dd"年月日的順序。
其中#user_profile_attributes_birthday這個(gè) HTML ID 可以透過 Chrome 按右鍵透過 Inspect 觀察得知:

這是成果:

如果需要支援多語言,可以指定語言:
$("#user_profile_attributes_birthday").datepicker({ format: "yyyy-mm-dd", language: "<%= I18n.locale %>" });
