I18nを使う基本的な流れは、こんな感じだね!
こんな感じで、日本語できるんだねー
en: general: greeting: morning: 'Good Morning.' hello: 'Hello, %{name}!'
ja: general: greeting: morning: 'おはようっす!' hello: 'こんにちは、%{name}さん!'
# config.i18n.default_locale = :de config.i18n.default_locale = :ja
<%= t 'general.greeting.morning' %> <%= t 'general.greeting.hello', :name => 'アンタ' %>
おはようっす! こんにちは、アンタさん!
上記の方法だと、サーバ単位で言語を設定されちゃうから、動的に変えたいよね!
class ApplicationController < ActionController::Base before_filter :detect_locale private def detect_locale I18n.locale = request.headers['Accept-Language'].scan(/^[a-z]{2}/).first end
private def default_url_options(options = {}) { :locale => I18n.locale } end def detect_locale I18n.locale = params[:locale] end
scope "(:locale)", :locale => /ja|en/ do resources :books match ':controller(/:action(/:id(.:format)))' end
match '/:locale' => 'books#index' root :to => 'books#index'
辞書は、結構いろいろと書けるみたい!こういうの、好き
ja: hello: i18n: message: メッセージだい!?
<%= t '.message' %>
ja: attributes: isbn: 'ISBNコード' title: '書名' price: '価格' publish: '出版社' published: '刊行日'
<%= f.label :isbn %><br />
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
元 | index.html.erb |
日本語 | index.ja.html.erb |
英語 | index.en.html.erb |
辞書を使う時に「t」を使うんで、そのオプション詳細ね。
scopeオプション :<%= t :morning, :scope => 'general.greeting' %><br /> scopeオプションの配列:<%= t :morning, :scope => [:general,:greeting] %><br /> 変数に入れれば、きれいに書ける?: <% k = [:general,:greeting] %><br /> <%= t :morning, :scope => k %><br />
デフォルト設定 :<%= t 'general.greeting.hey', :default => 'へい!' %><br /> デフォルトの配列:<%= t :hey, :default => [:default,'へーい!'] %><br />
ロケールの直設定:<%= t 'general.greeting.morning', :locale => 'en' %><br />
ja: result: one: 'ひとつ' other: '%{count}件'
1個の場合:<%= t 'result', :count => 1 %><br /> 3個の場合:<%= t 'result', :count => 3 %><br />
1個の場合:ひとつ 3個の場合:3件