title: I18n Internationalization

For developing the multi-language application, build-in I18n support by egg-i18n plugin

Default Language

Default en-US. Assume that we want to switch the default language to Simplified Chinese:

  1. // config/config.default.js
  2. exports.i18n = {
  3. defaultLocale: 'zh-CN',
  4. };

Switch Language

Here we have some ways to switch the application’s current language (Modified records will set to the cookie locale), the next request will use the language setting directly.

Priority from high to low:

  1. query: /?locale=en-US
  2. cookie: locale=zh-TW
  3. header: Accept-Language: zh-CN,zh;q=0.5

If want to modify parameter name of query or cookie

  1. // config/config.default.js
  2. exports.i18n = {
  3. queryField: 'locale',
  4. cookieField: 'locale',
  5. // Cookie default expired after one year, the unit is ms if set as Number
  6. cookieMaxAge: '1y',
  7. };

Writing I18n Multi-language Documents

Configuration of multi-language are independent, stored in config/locale/*.js

  1. - config/locale/
  2. - en-US.js
  3. - zh-CN.js
  4. - zh-TW.js

Not only take effects in the application directory, but also in the directory of framework or plugin config/locale

Note: It’s locale, not locals.

Example:

  1. // config/locale/zh-CN.js
  2. module.exports = {
  3. Email: '邮箱',
  4. };

Or using JSON file:

  1. // config/locale/zh-CN.json
  2. {
  3. "Email": "邮箱"
  4. }

Getting Multi-language Texts

Use __ (Alias: gettext) function to get the multi-language texts under locale directory

Note: `` is two underscores__

Take above multi-language configuration as example:

  1. ctx.__('Email')
  2. // zh-CN => 邮箱
  3. // en-US => Email

If texts contain format function like %s%j, we can call by the way similar to util.format()

  1. // config/locale/zh-CN.js
  2. module.exports = {
  3. 'Welcome back, %s!': '欢迎回来,%s!',
  4. };
  5. ctx.__('Welcome back, %s!', 'Shawn');
  6. // zh-CN => 欢迎回来,Shawn!
  7. // en-US => Welcome back, Shawn!

Support array, subscript and placeholder, such as

  1. // config/locale/zh-CN.js
  2. module.exports = {
  3. 'Hello {0}! My name is {1}.': '你好 {0}! 我的名字叫 {1}。',
  4. };
  5. ctx.__('Hello {0}! My name is {1}.', ['foo', 'bar'])
  6. // zh-CN => 你好 foo!我的名字叫 bar。
  7. // en-US => Hello foo! My name is bar.

Use in Controller

  1. class HomeController extends Controller {
  2. async index() {
  3. const ctx = this.ctx;
  4. ctx.body = {
  5. message: ctx.__('Welcome back, %s!', ctx.user.name)
  6. // or use gettext, it is a alias of __ function
  7. // message: ctx.gettext('Welcome back', ctx.user.name)
  8. user: ctx.user,
  9. };
  10. }
  11. }

Use in View

Assume we are using template engine Nunjucks

  1. <li>{{ __('Email') }}: {{ user.email }}</li>
  2. <li>
  3. {{ __('Welcome back, %s!', user.name) }}
  4. </li>
  5. <li>
  6. {{ __('Hello {0}! My name is {1}.', ['foo', 'bar']) }}
  7. </li>