I will write what I did when I tried to support English in web application I am developing.
Gemfile
gem 'rails-i18n'
Installation
bundle
config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
#Corresponding language. This time in Japanese(ja)And english(en)Only
config.i18n.available_locales = %i(ja en)
#If a language other than the above supported languages is specified, set whether to make an error
config.i18n.enforce_available_locales = true
#Default language
config.i18n.default_locale = :ja
controller
controller/application_controller.rb
before_action :set_locale
def set_locale
I18n.locale = locale
end
def locale
@locale ||= params[:locale] ||= I18n.default_locale
end
def default_url_options(options={})
options.merge(locale: locale)
end
routes.rb
routes.rb
scope '(:locale)', locale: /#{I18n.available_locales.map(&:to_s).join('|')}/ do
root "posts#index"
resources :posts
end
The part surrounded by scope is a page that supports multiple languages.
Create en.yml and ja.yml. For sentences that you want to multilingualize
views
<%= t(:hello) %>
Write. Feel free to change hello
ja.yml
ja:
hello:Hello
#All models start from activerecord.
#This will allow User.model_name.human / User.human_attribute_name({attr_name})Can be accessed with.
activerecord:
models:
user: 'User information'
attributes:
user:
name: 'name'
mail: 'mail address'
url: 'Web page'
en.yml
en:
hello: "hello"
#All models start from activerecord.
#This will allow User.model_name.human / User.human_attribute_name({attr_name})Can be accessed with.
activerecord:
models:
user: 'User'
attributes:
user:
name: 'Name'
mail: 'Email'
url: 'URL'
I will do it like this.
reference http://alfa.hatenablog.jp/entry/2013/12/03/221308
Recommended Posts