GT ClassMethodsFormatting

formatMessage

GT の formatMessage メソッドのAPIリファレンス

概要

formatMessage メソッドは、変数の挿入と locale に応じたフォーマットでメッセージを整形します。 Format.JS の intl-messageformat ライブラリの上に構築されており、ICU message format のパターンをサポートします。

このメソッドは変数の補間や複数形ルールに不可欠です。 また、数値や日付のフォーマットなどにも対応しています。

const gt = new GT({
  sourceLocale: 'en',
  targetLocale: 'fr'
});

const formatted = gt.formatMessage('こんにちは {name}、{count} 件のメッセージがあります', {
  variables: { name: 'Alice', count: 5 }
});
// 戻り値: "こんにちは Alice、5 件のメッセージがあります"

リファレンス

パラメータ

Prop

Type

options オブジェクト

プロパティ省略可説明
localesstring | string[]フォーマットに使用する Locale(インスタンスのデフォルトを上書き)
variablesFormatVariablesメッセージの補間に使用する variables を含むオブジェクト

FormatVariables 型

type FormatVariables = {
  [key: string]: string | number | Date | boolean;
};

返り値

string - 変数が差し込まれ、locale 固有の書式設定が適用された整形済みメッセージ。

動作

変数の置換

  • 単純な変数: {variableName} → 文字列値に置き換えられます
  • ICU パターン: {count, plural, ...} → ICU の書式ルールで処理されます
  • 変数が不足している場合: エラーになります
  • 二重の中括弧: 中括弧の挙動をエスケープし、単一の中括弧として表示されます

メッセージフォーマットのサポート

  • 単純な補間: {variable}
  • 数値の書式設定: {price, number, ::currency/USD}, {discount, number, percent}, {num, number, integer}
  • 日付の書式設定: {date, date, short}, {time, time, short}
  • 複数形ルール: {count, plural, =0 {none} =1 {one} other {many}}
  • 選択: {gender, select, male {he} female {she} other {they}}
  • 序数の選択 (selectordinal): {place, selectordinal, =1 {#st} =2 {#nd} =3 {#rd} other {#th}}

変数の基本的な置換

const gt = new GT({ targetLocale: 'en' });

const message = gt.formatMessage('ようこそ {name}!', {
  variables: { name: 'John' }
});
console.log(message); // "ようこそ John!"

ICU 形式による複数形

const message = gt.formatMessage(
  'カートに{count, plural, =0 {商品がありません} =1 {商品が1つあります} other {商品が#個あります}}',
  {
    variables: { count: 3 }
  }
);
console.log(message); // "カートに商品が3個あります"

数値と通貨のフォーマット

const gt = new GT({ targetLocale: 'en' });

const message = gt.formatMessage(
  'お支払い総額は {price, number, ::currency/USD} で、{discount, number, percent} 割引が適用されます',
  {
    variables: { 
      price: 99.99,
      discount: 0.15 
    }
  }
);
console.log(message); // "お支払い総額は $99.99 で、15% 割引が適用されます"

複雑なメッセージ テンプレート

const orderStatusMessage = gt.formatMessage(`
  注文 #{orderId} のステータス更新:
  - 商品: {itemCount, plural, =0 {商品なし} =1 {1点} other {# 点}}
  - 合計: {total, number, ::currency/USD}
  - ステータス: {status, select, 
      pending {処理中} 
      shipped {発送済み} 
      delivered {配達完了} 
      other {不明}}
  - 配達: {deliveryDate, date, short}
`, {
  variables: {
    orderId: 'ORD-12345',
    itemCount: 3,
    total: 149.97,
    status: 'shipped',
    deliveryDate: new Date('2024-03-20')
  }
});

注意事項

  • このメソッドは、Format.JS の Intl.MessageFormat を使用して、ICU message format 構文を処理し、高度な書式設定を行います。
  • 欠落している variables は Error をスローします。
  • ロケールに応じた数値・日付・通貨の書式設定が自動的に適用されます。

次のステップ

このガイドはどうでしたか?

formatMessage