Adding Translation to a Rails Application
Hi friends, in my previous blogs related to internationalization of rails application, we have configured the i18N api and saw different types of methods to pass the locals, if you have not read those then first read them, before directly switching to this, their links are given at the end of this article
Now lets internationalize our application by adding translations to it. Suppose we have already configured i18N and our controller and before_filter methods to apply localization are like:
# config/routes.rb
Rails.application.routes.draw do
root to: "home#welcome"
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :apply_locale
def apply_locale
I18n.locale = params[:locale] || I18n.default_locale
end
end
# app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
def welcome
flash[:notice] = t(:flash_msg)
end
end
# app/views/welcome/welcome.html.erb
<h1>This is the world of rails</h1> # = > This is the world of rails
<p><%= flash[:notice] %></p> # = > This is a Flash Message
To apply translation, there is a 't' helper available in rails for translation. For applying this we need to pass translation keys in place of actual string and need to map them.
In your file you can define the keys as:
# config/locales/en.yml
en:
rails_world: This is the world of rails
flash_msg: This is a Flash Message
# config/locales/pirate.yml
pirate:
rails_world: This be a world o' rails
flash_msg: This be a Flash Message
Then if you hit http://www.localhost:3000, you will get this page:
and if you hit http://www.localhost:3000?locale=pirate, you will get this:
You can also pass variables inside translation messages. You can do it like:
#inside en.yml
en:
flash_msg: This is a Flash Message
rails_world: This is a world of rails
first_message: "Hi %{username}, %{message}"
#inside view welcome.html.erb
<h1><%=t 'first_message', username: "Reader", message: "Did this example worked ?" %></h1>
<h2><%=t :rails_world %></h2>
<p><%= flash[:notice] %></p>
A open source git project of this example can be obtained here:
Rails Translation Example
Other articles related to internationalization are available here:
0 Comment(s)