4 min. read
Rails GetText Syntax Overview
In this article, we will give you a quick overview of how to translate your Rails application with the GetText syntax. There is only a few (short-named) methods to remember, we will make you love underscores!
TL;DR
Singular | _("text") |
Plural | n_("singular text", "plural text", number) |
Singular with context | p_("context", "text") |
Plural with context | np_("context", "singular text", "plural text", number) |
Simple Texts
_
is the base method you will use everywhere.
In a controller :
class PostsController < ActionController::Base
def create
...
flash[:notice] = _('Post successfully saved')
redirect_to posts_path
end
end
In a view :
<h1><%= _('Create a New Post') %></h1>
<%= f.label :title, _('Title') %>
In a model validation :
class Post < ApplicationRecord
validates :title, :presence => {
:message => lambda { _('Title is mandatory.') }
}
end
Note that the call was wrapped into a lambda because otherwhise it would have been statically evaluated.
Interpolations
Interpolations can be easily performed using the standard %
operator.
Find some examples below.
_('Hi %{name}, do you like violence?') % { name: "Steve" }
_('%{city1} is bigger than %{city2}') % { city1: "NYC", city2: "BXL" }
Plural Forms
If the translatable string is depending on the number of items, use _n
.
It takes three arguments : the singular form, the plural form, and the
cardinality.
For example :
n_("There is a mouse in our house.", "There are some mice in our house.", @mice.size)
And you can of course combine with interpolations :
n_("There is a mouse.", "There are %{num} mice.", @mice.size) % { num: @mice.size }
Translation Contexts
Sometimes you would need to scope a given translation to a given part of you application. For instance in order to be able to translate a given string differently depending on the context.
There are two dedicated methods for that : p_
(singular with context)
and np_
(plural with context). They take the same arguments as _
and
n_
(respectively) with an extra string argument defining the context
added before.
Here is an example :
p_("Menu", "Open file")
p_("Menu", "Close file")
With plurals and interpolations :
np_("Menu", "Open a file", "Open %{n} files", 4) % { n: 4 }
If you are wondering why it is p for defining a context, that is because it stands for prefix.
Other Syntaxes
Some other special usages of GetText
can also be used but won’t be detailed here because they are very specific
(and not so useful) : s_
, ns_
, N_
and Nn_
.