# node: getTranslations URL: https://generaltranslation.com/zh/docs/node/api/get-translations.mdx --- title: getTranslations description: getTranslations 字典翻译函数的 API 参考 --- ## 概述 `getTranslations` 返回一个翻译函数 `t`,用于从[字典](/docs/next/guides/dictionaries)中查找条目。 使用它可通过字典键翻译预定义的字符串。 ```js import { getTranslations } from 'gt-node'; const t = await getTranslations(); t('greeting.hello'); // "Hello!" ``` **必须提供请求上下文:** `getTranslations` 必须在 [`withGT`](/docs/node/api/with-gt) 回调中调用,这样它才能确定应使用哪个区域设置。 ## 参考 ### 参数 无。 ### 返回值 一个 Promise,其解析结果为翻译函数 `t`: ```ts Promise ``` `t` 函数接受一个字典键和可选的插值选项: | 名称 | 类型 | 说明 | | ---------- | ------------------------------ | --------------- | | `id` | `string` | 指向字典条目的以点分隔的路径。 | | `options?` | `DictionaryTranslationOptions` | 用于插值的变量。 | **返回值:** `string` — 翻译后的文本 (或源语言的后备内容) 。 如果该键在源字典中不存在,`t()` 会抛出错误。 如果该键存在于源字典中,但当前区域设置没有对应的翻译,`t()` 会返回源文本。 ### `t.obj()` 返回字典中的整个子树对象,而不是单个字符串。 ```ts t.obj(id: string): DictionaryObjectTranslation ``` | 名称 | 类型 | 描述 | | ---- | -------- | ------------ | | `id` | `string` | 以点分隔的字典子树路径。 | **返回:**与字典结构对应的嵌套对象;有可用译文的值会返回译文,其余则返回源语言后备内容。 *** ## 设置 ### 自动 (推荐) 在项目根目录下创建一个 `dictionary.json` 文件: ```json title="dictionary.json" { "greeting": { "hello": "Hello!" }, "user": { "welcome": "Welcome, {name}!" } } ``` 当你运行 `npx gtx translate` 时,CLI 会自动检测 `dictionary.json`,并将其翻译为你已配置的区域设置。 然后用该字典初始化 GT: ```ts import { initializeGT } from 'gt-node'; import dictionary from './dictionary.json'; initializeGT({ dictionary, defaultLocale: 'en-US', locales: ['en-US', 'es', 'fr'], }); ``` ### 自定义字典加载器 如果你自行管理翻译后的 字典,请将 `loadDictionary` 函数传给 [`initializeGT`](/docs/node/api/initialize-gt): ```ts import { initializeGT } from 'gt-node'; import dictionary from './dictionary.json'; initializeGT({ dictionary, loadDictionary: async (locale) => { const dict = await import(`./locales/${locale}.json`); return dict.default; }, }); ``` 通过 `loadDictionary` 加载的翻译优先于 GT 生成的翻译。 *** ## 示例 ### 基本用法 ```ts import { getTranslations } from 'gt-node'; const t = await getTranslations(); t('greeting.hello'); // "Hello!" ``` ### 变量插值 ```ts const t = await getTranslations(); t('user.welcome', { name: 'Alice' }); // "欢迎,Alice!" ``` ### 使用 `t.obj()` 查找对象 ```ts const t = await getTranslations(); const errors = t.obj('errors'); // { notFound: "页面未找到", unauthorized: "访问被拒绝" } ``` *** ## 注意事项 * `getTranslations` 是 [`getMessages`](/docs/node/api/get-messages) 在基于字典场景下对应的函数,后者用于内联 `msg()` 字符串。 * Next.js 中对应的版本请参见 [gt-next 中的 `getTranslations`](/docs/next/api/dictionary/get-translations)。