GT ClassMethodsFormatting
formatMessage
GT formatMessage 方法的 API 参考
概览
formatMessage 方法用于通过变量替换并结合 locale 感知的规则来格式化消息。
它基于 Format.JS 的 intl-messageformat 库构建,支持 ICU 消息格式模式。
该方法对变量插值和复数化处理至关重要。 它还支持数字和日期等格式化功能。
const gt = new GT({
  sourceLocale: 'en',
  targetLocale: 'fr'
});
const formatted = gt.formatMessage('你好 {name},你有 {count} 条消息', {
  variables: { name: 'Alice', count: 5 }
});
// 返回:"你好 Alice,你有 5 条消息"参考
参数
Prop
Type
Options 对象
| 属性 | 类型 | 可选 | 描述 | 
|---|---|---|---|
| locales | string | string[] | ✓ | 用于格式化的 locale(会覆盖实例默认值) | 
| variables | FormatVariables | ✓ | 包含用于消息插值的变量的对象 | 
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}
- 复数化(pluralization):{count, plural, =0 {无} =1 {一} other {多}}
- 条件选择:{gender, select, male {他} female {她} other {TA}}
- 序数选择(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 格式处理复数(pluralization)
const message = gt.formatMessage(
  '您的购物车中有 {count, plural, =0 {没有商品} =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 消息格式语法,以实现高级格式化。
- 缺失的 variables 会抛出 Error。
- 将自动应用基于 locale 的数字、日期和货币格式。
下一步
- 查看 Intl.MessageFormat文档 以了解更多 options
- 使用 formatNum 来格式化数字
这份指南怎么样?

