# gt-node: General Translation Node.js SDK: 翻译字符串 URL: https://generaltranslation.com/zh/docs/node/guides/translating-strings.mdx --- title: 翻译字符串 description: 如何在 gt-node 中使用 General Translation 翻译处理函数字符串、已注册的 messages 和动态内容。 related: links: - /docs/node/guides/detecting-locale - /docs/node/guides/storing-translations - /docs/node/guides/configuring --- `gt-node` 提供了三种翻译字符串的方式。具体使用哪一种,取决于字符串出现在哪里,以及是否能预先确定。 *注意:这三种方式都在 [`withGT`](/docs/node/guides/detecting-locale) 层级内运行,因此能够识别请求的区域设置。* ## 使用 `getGT` 翻译处理函数中的字符串 [#get-gt] 对于直接写在处理函数中的字符串,先 await [`getGT`](/docs/node/reference/functions/get-gt) 获取翻译函数,再调用它。使用 ICU 占位符插入变量值。 ```ts import { getGT } from 'gt-node'; app.get('/api/greeting', async (req, res) => { const gt = await getGT(); res.json({ message: gt('Hello, world!'), welcome: gt('Welcome, {name}!', { name: 'Alice' }), }); }); ``` 这是单次使用字符串的默认选择。添加 `$context` 以为术语消歧。 ## 使用 `msg` 复用已注册的消息 [#msg] 对于在处理函数之外定义的字符串 (如共享常量、错误消息和枚举) ,请在模块层级中使用 [`msg`](/docs/node/reference/functions/msg) 注册它们,然后通过 [`getMessages`](/docs/node/reference/functions/get-messages) 获取对应内容。 ```ts import { msg, getMessages } from 'gt-node'; const NOT_FOUND = msg('Resource not found.'); app.use(async (req, res) => { const m = await getMessages(); res.status(404).json({ error: m(NOT_FOUND) }); }); ``` ## 使用 `tx` 翻译动态内容 [#tx] 对于无法预先确定且未预先生成的内容,请使用 [`tx`](/docs/node/reference/functions/tx) 在 Runtime 进行翻译。它会在缓存未命中时发起网络请求,因此只应将其用于真正的动态字符串。 ```ts import { tx } from 'gt-node'; const translated = await tx(`Status: ${status}`); ``` *注意:`tx` 不使用 ICU 占位符——请先用 template literal 嵌入值,再调用。* ## 选择一种方案 [#choose] * 一次性的处理函数 string → `getGT`。 * 共享的常量和错误信息 → 使用 `msg` 搭配 `getMessages`。 * 动态且不可预知的内容 → `tx`。 * 集中管理、基于键的文案 → 使用 dictionary 和 [`getTranslations`](/docs/node/reference/functions/get-translations)。 ## Next steps - /docs/node/guides/detecting-locale - /docs/node/guides/storing-translations - /docs/node/guides/configuring