選用了Locale作爲國際化的解決方案。
1、首先是安裝
- gem install locale_rails
會自動的安裝locale和locale_rails兩個gem。
2、生成i18n的配置文件
- # in config/initializer/locale.rb
- # Tell the I18n library where to find your translations
- I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
- # Tell the supported locales. This is the one of additional setting by Ruby-Locale for Ruby on Rails.
- # If supported_locales is not set, the locale information which is given by WWW browser is used.
- # This setting is required if your application wants to restrict the locales.
- I18n.supported_locales = Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ].collect{|v| File.basename(v, ".*")}.uniq
- # Tell the default locale. If this value is not set, "en" is set.
- # With this library, this value is used as the lowest priority locale
- # (If other locale candidates are not found, this value is used).
- I18n.default_locale = "en-US"
3、gem的引用
- # config/environment.rb
- Rails::Initializer.run do |config|
- :
- :
- config.gem 'locale'
- config.gem 'locale_rails'
- end
app/controllers/application.rb中不需要定義set_locale。
4、基本知識
- I18n.translate "hello"
- I18n.localize Time.now
- # 簡寫
- I18n.t "hello"
- I18n.l Time.now
多國語文件默認的放在config/localese文件夾下,假設你要支持中文和英語,那麼你需要在這個文件夾下放置en.yml和zh.yml。
- # zh-CN.yml
- "zh-CN":
- submit: '提交'
- create: '創建'
- #en.yml
- en:
- submit: 'Submit'
- create: 'Create'
試圖中更加簡單,你可以直接調用t方法:
- <%= t 'submit' %>
5、使用
你可以進入Console進行測試:
=> "Submit"
> I18n.locale = 'zh'
=> "zh"
> I18n.t('submit')
=> "提交"
6、傳遞變量
有些時候,我們的字符串中可能需要包含變量,只需要將其放在兩個大括號內就可以了:
- # zh-CN.yml
- "zh-CN":
- hello: "你好, {{name}}"
打開console:
=> "你好,Rails!"
還可以進行單複數處理、時間和日期本地化、貨幣處理、ActiveRecord和route處理。
解決問題
1、undefined method set_app_language_tags錯誤
方法:http://github.com/mutoh/locale_rails/issues/#issue/2
2、translation_missing錯誤
千萬要記住日文是ja,簡體中文是zh-CN,爲了這個鬱悶了好久
參考:
http://guides.rubyonrails.org/i18n.html
http://github.com/svenfuchs/rails-i18n (多國語文件)
http://www.yotabanana.com/hiki/ruby-locale-rails-howto.html
http://www.letrails.cn/archives/rails-2-2-i18n-tutorials/
http://d.hatena.ne.jp/willnet/20100430/1272618929
轉載地址:http://ilgnep.iteye.com/blog/686353