GT ClassMethodsFormatting
formatMessage
GT formatMessage 方法的 API 参考
概览
formatMessage 方法用于对消息进行变量替换,并根据 locale 执行本地化格式化。
它基于 Format.JS 的 intl-messageformat 库构建,支持 ICU 消息格式模式。
该方法是变量插值和复数规则(pluralization)的核心。 它还支持数字和日期等格式化功能。
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} - 复数处理:
{count, plural, =0 {none} =1 {one} other {many}} - 条件选择:
{gender, select, male {he} female {she} other {they}} - 序数选择:
{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 {中有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 消息格式语法,实现高级格式化。 - 缺失变量将抛出错误。
- 会自动应用特定 locale 的数字、日期和货币格式
后续步骤
- 查看
Intl.MessageFormat文档 以了解更多 options - 使用 formatNum 格式化数字
本指南如何?