I18n With Ruby On Rails 5

ADVERTISEMENT

 
 
 
i18n with Ruby on Rails 5
Tutorial
Step 1: Set your default locale (language code), if not :en (Default = English) in config/application.rb
Step 2: Create a YAML file with the correct locale as root key in the config/locales directory. You can
name it after the language’s ISO code, e.g. de.yml:
de:
hello:
“Hallo Welt”
Step 3: Use the i18n key in your views or controllers.
View
Controller
<h1><%=t
‘hello’
%></h1>
flash[:notice] = t(‘hello’)
Rails adds a t (translate) helper method to your views so that you do not need to spell
out I18n.t all the time. Additionally this helper will catch missing translations and wrap the
resulting error message into a <span class="translation_missing">.
Step 4: Manage the locale across requests by defining a before action in the
ApplicationController.
before_action :set_locale
def
set_locale
I18n.locale = params[:locale] || I18n.default locale
end
If the locale is set via the URL to the de locale ( ), the
response renders the German strings.
def
default_url_options
{ locale: I18n.locale }
end
If you want to have an URL like , which is RESTful and in accord with
the rest of the World Wide Web, it does require a little bit more work to implement.
scope “(:locale)”, locale:
/en|de/
do
Root to:
‘welcome#index’
end
Quick Summary
No strings or other locale specific settings should be used in the views, models and
!
controllers. These texts should be moved to the YAML files in the config/locales directory.
Use the short form of the I18n methods: I18n.t instead of I18n.translate and I18n.l
!
instead of I18n.localize.
Use "lazy" lookup and dot-separated keys in the controllers and models instead of specifying
!
the :scope option. The dot-separated call is easier to read and traces the hierarchy.
When the labels of an ActiveRecord model need to be translated, use the activerecord scope.
!
Do not store the chosen locale in a session or a cookie. The locale should be transparent and
!
a part of the URL.
Make your URLs beautiful and RESTful by adding a :locale scope to your routes.
!
MADE WITH
BY LINGOHUB

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go