# node: getGT URL: https://generaltranslation.com/zh/docs/node/api/get-gt.mdx --- title: getGT description: getGT 字符串翻译函数的 API 参考文档 --- ## 概述 `getGT` 函数是一个异步函数,会返回一个用于翻译字符串的函数。 它会解析由 GT 编译器在构建阶段注册的翻译。 ```js import { getGT } from 'gt-node'; const gt = await getGT(); const greeting = gt('Hello, world!'); ``` **必须提供请求上下文:** 必须在 [`withGT`](/docs/node/api/with-gt) 回调内调用 `getGT`,这样它才能知道应使用哪个区域设置。 ## 参考 ### 参数 无。 ### 返回值 一个 Promise,对应一个翻译函数 `gt`: ```ts Promise<(content: string, options?: InlineTranslationOptions) => string> ``` | 名称 | 类型 | 说明 | | ---------- | -------------------------- | ------------------- | | `content` | `string` | 要翻译的字符串。 | | `options?` | `InlineTranslationOptions` | 可选的翻译选项 (变量、上下文等) 。 | `gt` 函数会返回翻译后的字符串;如果未找到翻译,则返回原始字符串。 #### `InlineTranslationOptions` | 属性 | 类型 | 说明 | | ------------ | -------- | ---------------------- | | `$context?` | `string` | 用于帮助消除翻译歧义的附加上下文。 | | `$id?` | `string` | 翻译条目的自定义 ID。 | | `$maxChars?` | `number` | 译文的最大字符数。 | | Other keys | `any` | 按 `{key}` 语法插入字符串的变量值。 | *** ## 示例 ### 简单翻译 ```js title="handler.js" import { withGT, getGT } from 'gt-node'; function handleRequest(locale: string) { return withGT(locale, async () => { const gt = await getGT(); return gt('Hello, world!'); }); } ``` ### 使用变量 在字符串中使用 `{variableName}` 语法,并通过选项对象传入相应的值: ```js title="handler.js" import { withGT, getGT } from 'gt-node'; function handleGreeting(locale: string, name: string) { return withGT(locale, async () => { const gt = await getGT(); return gt('Hello, {name}!', { name }); }); } ``` ### 使用 ICU 消息格式 `gt-node` 支持 ICU 消息格式,可进行高级格式化: ```js title="handler.js" const gt = await getGT(); const balance = gt( 'Your balance: {amount, number, ::currency/USD}', { amount: 1234.56 } ); ``` *** ## 说明 * `getGT` 会返回一个**构建时**翻译函数。字符串会在部署前的 CD 流程中完成翻译。 * 在开发环境中,翻译会按需执行 (需要 Dev API 密钥) 。 * 如果未找到翻译,将返回原始字符串作为后备。 ## 后续步骤 * 如需解析预注册的消息,请参阅 [`getMessages`](/docs/node/api/get-messages)。 * 如需设置区域设置上下文,请参阅 [`withGT`](/docs/node/api/with-gt)。