Internationalization

Internationalization Files

In plugins, multi-language files for both frontend and backend are stored in the src/locale folder

|- /plugin-sample-i18n
  |- /src
    |- /locale      # Multi-language folder
      |- en_US.ts   # English language
      |- zh_CN.ts   # Chinese language

You can add translation entries in the corresponding multi-language file (/src/locale/${lang}.ts). If it's a newly added multi-language file, you need to restart the application for it to take effect. You can check the app:getLang interface to verify if the translation entries have been successfully added.

http://localhost:3000/api/app:getLang?locale=zh-CN

How to Support Internationalization

The server has two i18n instances: app.i18n and ctx.i18n

app.i18n

app.i18n is the global i18n instance, generally used in CLI. For example, combined with inquirer to implement command-line interactions.

import select from '@inquirer/select';
import input from '@inquirer/input';

export class PluginSampleI18nServer extends Plugin {
  load() {
    this.app.command('test-i18n').action(async () => {
      const answer1 = await select({
        message: 'Select a language',
        choices: [
          {
            name: '中文',
            value: 'zh-CN',
          },
          {
            name: 'English',
            value: 'en-US',
          },
        ],
      });
      await this.app.changeLanguage(answer1);
      const answer2 = await input({
        message: app.i18n.t('Enter your name'),
      });
      console.log(app.i18n.t(`Your name is {{name}}`, { name: answer2 }));
    });
  }
}

ctx.i18n

A cloneInstance of the global app.i18n, each request's ctx is completely independent, responding with multi-language information based on the client's language.

Client request parameters can be placed in the query string

GET /?locale=en-US HTTP/1.1
Host: localhost:3000

Or in request headers (recommended)

GET / HTTP/1.1
Host: localhost:3000
X-Locale: en-US

Example

export class PluginSampleI18nServer extends Plugin {
  load() {
    this.app.use(async (ctx, next) => {
      if (ctx.path === '/api/test-i18n') {
        ctx.body = `${ctx.i18n.t('Hello')} ${ctx.i18n.t('World')}`;
      }
      await next();
    });
  }
}

View http://localhost:3000/api/test-i18n?locale=zh-CN

API

TachybaseBase's i18n is based on i18next. For detailed usage, refer to I18next API Documentation. Below are just a few important examples

i18n.t()

Each plugin's locale is distinguished by ns, where ns is the plugin name, such as:

t('Hello', { ns: '@tachybase/plugin-sample-i18n' });

i18n.changeLanguage()

Change the current language

await i18n.changeLanguage('en-US');

Complete Plugin Example

Total visits  times     Total visitors  times     Total reading  times.   Powered by Tego Team