i18n 国际化

NocoBase 插件支持前后端多语言国际化(i18n),你可以通过统一的机制在插件中实现多语言内容。

多语言文件管理

插件的多语言文件统一存放在 src/locale 目录下,按语言命名,比如:

|- /plugin-hello
  |- /src
    |- /locale
      |- en-US.json   # 英文
      |- zh-CN.json   # 中文

每个语言文件导出一个 JSON 对象,包含该语言的所有翻译词条,比如:

// zh-CN.json
{
  "Hello": "你好",
  "World": "世界",
  "Enter your name": "请输入你的名字",
  "Your name is {{name}}": "你的名字是 {{name}}"
}
// en-US.json
{
  "Hello": "Hello",
  "World": "World",
  "Enter your name": "Enter your name",
  "Your name is {{name}}": "Your name is {{name}}"
}
提示

初次添加语言文件,需要重启应用才能生效。你可以通过接口校验翻译词条是否生效: http://localhost:13000/api/app:getLang?locale=zh-CN

全局 i18n 实例

app.i18n 是全局 i18n 实例,适用于 CLI 或插件全局场景。你可以结合 inquirer 实现命令行交互:

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 }));
    });
  }
}

app.i18n.t(text, options) 用于翻译文本,并支持模板变量。

请求上下文 i18n

每个请求的 ctx.i18n 是全局 i18n 的克隆实例,根据客户端语言独立响应多语言信息。

设置客户端语言

  • Query String:
GET /?locale=en-US HTTP/1.1
Host: localhost:13000
  • Request Header(推荐):
GET / HTTP/1.1
Host: localhost:13000
X-Locale: en-US

在中间件中使用

export class PluginSampleI18nServer extends Plugin {
  load() {
    this.app.use(async (ctx, next) => {
      if (ctx.path === '/api/test-i18n') {
        ctx.body = ctx.t('Hello', { ns: '@my-project/plugin-hello' });
      }
      await next();
    });
  }
}

访问 http://localhost:13000/api/test-i18n?locale=zh-CN 会返回 你好

插件内部 i18n

插件内部可以直接用 plugin.t(key, options) 来获取翻译:

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

plugin.t(text) 等价于 ctx.t(text, { ns })

相关链接