--Japanese-English correspondence as easily as possible
A button has been installed on the header for easy switching.
erb:application.html.erb
Install the following in the header
<% if session[:locale] == "en" || session[:locale].blank? %>
<%= link_to "/home/change_language/ja" do %>
Japanese
<% end %>
<% elsif session[:locale] == "ja" %>
<%= link_to "/home/change_language/en" do %>
English
<% end %>
<% end %>
This time only Japanese and English are supported
--"English" if "ja" is included in session [: locale] --"Japanese" if "en" is included in session [: locale]
Is displayed.
routes.rb
get "/home/change_language/:language" => "home#change_language"
home_controller.rb
def change_language
session[:locale] = params[:language]
redirect_back(fallback_location: "/")
end
By setting before_action, the language information will be set first no matter which page you access.
application.rb
before_action :set_locale
private
def set_locale
if %w(ja en).include?(session[:locale])
I18n.locale = session[:locale]
end
end
I wrote the translation separately for. Example) English only changes ja to en.
ja.yml
ja:
#Commonly used words
dictionary:
words:
hello: "Hello"
activerecord:
#Model name
model:
user: "user"
#Column name
attributes:
user_name: "User name"
password: "password"
#Set for each view
users:
show:
profile: "profile"
picture: "Photo"
form:
required_field: "Required item"
erb:show.html.erb
<%= t("dictionary.words.hello") %> =>Hello
<%= t("activerecord.attributes.user_name") %> =>User name
#When View is users show, it can be abbreviated as follows.
<%= t(".profile") %> =>profile
<%= t(".picture") %> =>Photo
#If you set the column name, even the form helper will automatically switch depending on the language
<%= form_with scope: @user ,,,,,%>
<%= form.label :user_name %> =>User name
<% end %>
erb:_form.html.erb
#Partial is used without underscore View is users_form.html.For erb
<%= t(".required_field") %> =>Required item
#This partial is users show.html.Even if it is used in erb
<%= t(".picture") %> =>× This is not available.
Recommended Posts