Tip

このドキュメントはAIによって翻訳されました。不正確な情報については、英語版をご参照ください

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}}"
}

初めて言語ファイルを追加した場合は、変更を反映させるためにアプリケーションを再起動する必要があります。翻訳エントリが有効になっているかは、以下のAPIで確認できます。 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 インスタンスのクローンであり、クライアントの言語に基づいて多言語情報を個別に返します。

クライアント言語の設定

  • クエリ文字列:
GET /?locale=en-US HTTP/1.1
Host: localhost:13000
  • リクエストヘッダー(推奨):
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 }) と同等です。

関連API

  • app.i18n
  • app.t(text, options)
  • ctx.i18n
  • ctx.t(text, options)
  • plugin.t()
  • tExpr(text, options)