Skip to content

i18n multiple language support

allebaria edited this page Jan 27, 2020 · 1 revision

Why are we using it?

If we want to grow and our application runs in different countries we'll have to provide a multiple languages feature. By now, we'll only work in English but we'll set up the API so it can respond to more languages in the future.

How to use it?

The configuration has been carried out so the translations are set in config/locales/. Inside this folder, we'll have different locales files. Furthermore, we can establish a file hierarchy like this:

|-defaults
|---es.yml
|---en.yml
|-models
|---room
|-----es.yml
|-----en.yml
|-requests
|---defaults
|-----es.yml
|-----en.yml
|---rooms
|-----es.yml
|-----en.yml
|---locations
|-----es.yml
|-----en.yml

For instance, an en.yml will contain translations for English. This file could look like the code below:

en:
  rooms_errors:
    room_not_found: "Room was not found"

Later on, if we want to get a translated string, we would call it like so:

I18n.t('rooms_errors.room_not_found') # --> "Room was not found"

In addition, we can also pass arguments to the yml files:

en:
  room_model:
    price: "$%{price}"

With the example above, we could define a specific currency depending on the language. Then, we could call I18n like so:

I18n.t('room_model.price', price: @room.price) # --> "$40"
Clone this wiki locally