【Rails】i18n による日本語化対応
はじめに
Railsのi18nによるアプリの日本語化対応の仕方を備忘録として残しておく。
基本的な設定
まず、言語設定とロケールファイルの読み込み設定を行う。
# config/application.rb # 言語設定 この設定を行なっていないと日本語を表示してくれない config.i18n.default_locale = :ja # 複数ロケールファイルが読み込む設定 参照するファイルのパスを設定している。 config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
※ この設定で読み込む対象のファイルを増やすことができます。 locale/ja.yml以外に「モデルに関連する内容のみを記載するlocale/appricationrecord/ja.yml」や「Viewの表示のみの内容を記載するlocale/view/ja.yml」など、i18nの定義ファイルを分けて設定出来ます。
基本的な使い方
#config/locales/veiws/ja.yml ファイルを作成 ja: defaults: login: 'ログイン' register: '登録' logout: 'ログアウト' users: new: title: 'ユーザー登録' to_login_page: 'ログインページへ'
この設定で「ログイン」と表示したい場合は、
<%= t('defaults.login') %>
で「ログイン」と表示される。
また、「ユーザー登録」と表示したい場合は、
<%= t('users.new.title') %>
で「ユーザー登録」と表示される。
lazy lookupを使うとより簡単にかけます。
<%= t('users.new.title') %> <%= t('.title') %> #lazy lookup
モデル
#config/locales/activerecord/ja.yml ファイルを作成 ja: activerecord: models: user: 'ユーザー' board: '掲示板' attributes: user: last_name: '姓' first_name: '名' email: 'メールアドレス' password: 'パスワード' password_confirmation: 'パスワード確認'
この設定で「掲示板」と表示したい場合は、
<%= t('activerecord.models.user') %>
で「掲示板」と表示される。
また、「パスワード」と表示したい場合は、
<%= t('activerecord.attributes.password') %>
で「パスワード」と表示される。
2つのメソッド
Model.model_name.humanとModel.human_attribute_nameの2つのメソッドの使用方法
ja.yml
ja: activerecord: models: user: ユーザ attributes: user: name: 名前
Model.model_name.human
モデル名を指定
# t("activerecord.models.user")と同じ User.model_name.human #=> "ユーザ"
Model.human_attribute_name
attributes(属性)を指定
# t("activerecord.attributes.user.name")と同じ User.human_attribute_name :name #=> "名前"