# General Translation Platform: formatMessage URL: https://generaltranslation.com/zh/docs/platform/core/reference/gt-class-methods/formatting/format-message.mdx --- title: formatMessage description: 使用变量和符合区域设置的值格式化 ICU 风格的消息。formatMessage 的 API 参考。 --- 在 [GT](/docs/platform/core/reference/gt-class/constructor) 实例上,使用变量替换和符合区域设置的格式对消息进行格式化。General Translation 基于 Format.JS 的 [`intl-messageformat`](https://formatjs.github.io/docs/intl-messageformat/) 库,支持 ICU 消息格式模式,包括变量插值、复数处理、数字格式化和日期格式化。 ## 概览 [#overview] 在 [`GT`](/docs/platform/core/reference/gt-class/constructor) 实例上调用 `formatMessage`,传入消息字符串,以及一个可选的选项对象,其中包含用于插值的 `variables`。该方法会返回格式化后的消息。 ```typescript const gt = new GT({ sourceLocale: 'en', targetLocale: 'fr' }); const formatted = gt.formatMessage('Hello {name}, you have {count} messages', { variables: { name: 'Alice', count: 5 }, }); // "Hello Alice, you have 5 messages" ``` 签名: ```typescript formatMessage( message: string, options?: { locales?: string | string[]; variables?: FormatVariables; dataFormat?: StringFormat; } ): string ``` *注意:`formatMessage` 会在本地使用 `IntlMessageFormat` (来自 `intl-messageformat`) 运行,无需 API Key。提供 `locales` 时,它会覆盖该实例的区域设置。若要在没有 `GT` 实例的情况下进行格式化,请参阅独立使用的 [`formatMessage`](/docs/platform/core/reference/utility-functions/formatting/format-message)。* ## 工作原理 [#how-it-works] * **ICU 处理。** 该方法使用 `IntlMessageFormat` (来自 `intl-messageformat`) 解析 ICU 消息格式语法,并自动应用与区域设置相关的数字、日期和货币格式化。 * **区域设置解析。** `locales` 会在单次调用时覆盖实例的默认值。 * **缺失变量会抛出错误。** 如果消息中引用了某个变量,但该变量未在 `variables` 中提供,就会抛出错误。 * **转义花括号。** 按照 ICU 语法,用单引号包裹字面量花括号 (`'{'` 或 `'}'`) ,这样它就不会被视为占位符的起始符号。 ### 变量替换 * 简单变量:`{variableName}` 会被替换为字符串。 * ICU 模式:`{count, plural, ...}` 会按照 ICU 格式化规则处理。 * 缺失变量:会报错。 * 字面花括号:按 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}}` ## 参数 [#parameters] | 参数 | 描述 | 类型 | 可选 | 默认值 | | --------------------- | --------------- | -------- | -- | --- | | [`message`](#message) | 要格式化的 ICU 风格消息。 | `string` | 否 | — | | [`options`](#options) | 格式化配置,包括变量。 | `object` | 是 | — | ### `message` [#message] **类型** `string` · **必填** 使用 ICU 消息格式语法编写的待格式化消息。 ### `options` [#options] **类型** `object` · **可选** 格式化配置: | 名称 | 描述 | 类型 | 可选 | 默认值 | | ------------ | ----------------------------------------------- | -------------------- | -- | ------- | | `locales` | 用于格式化的区域设置 (覆盖实例默认值) 。 | `string \| string[]` | 是 | 实例区域设置 | | `variables` | 用于消息插值的变量对象。 | `FormatVariables` | 是 | `{}` | | `dataFormat` | 消息字符串的数据格式 (`'ICU'`、`'I18NEXT'` 或 `'STRING'`) 。 | `StringFormat` | 是 | `'ICU'` | `FormatVariables` 类型: ```typescript type FormatVariables = Record; ``` ## 返回值 [#returns] **类型** `string` 格式化后的消息,其中变量已完成替换,并应用了与区域设置相关的格式。 ## 示例 [#examples] ```typescript // 基本变量替换 const gt = new GT({ targetLocale: 'en' }); const message = gt.formatMessage('Welcome {name}!', { variables: { name: 'John' }, }); console.log(message); // "Welcome John!" ``` ```typescript // 使用 ICU 格式处理复数处理 const message = gt.formatMessage( 'You have {count, plural, =0 {no items} =1 {one item} other {# items}} in your cart', { variables: { count: 3 }, } ); console.log(message); // "You have 3 items in your cart" ``` ```typescript // 数字和货币格式化 const gt = new GT({ targetLocale: 'en' }); const message = gt.formatMessage( 'Your total is {price, number, ::currency/USD} with {discount, number, percent} off', { variables: { price: 99.99, discount: 0.15, }, } ); console.log(message); // "Your total is $99.99 with 15% off" ``` ```typescript // 复杂消息模板 const orderStatusMessage = gt.formatMessage(` Order #{orderId} status update: - Items: {itemCount, plural, =0 {no items} =1 {one item} other {# items}} - Total: {total, number, ::currency/USD} - Status: {status, select, pending {Pending} shipped {Shipped} delivered {Delivered} other {Unknown}} - Delivery: {deliveryDate, date, short} `, { variables: { orderId: 'ORD-12345', itemCount: 3, total: 149.97, status: 'shipped', deliveryDate: new Date('2024-03-20'), }, }); ``` ## 说明 [#notes] * 该方法使用 `IntlMessageFormat` (来自 `intl-messageformat`) 处理 ICU 消息格式 syntax。 * 缺少变量时会报错。 * 会自动应用区域设置相关的数字、日期和货币格式化。 * 如需格式化独立数字,请使用 [`formatNum`](/docs/platform/core/reference/gt-class-methods/formatting/format-num)。