# gt-next: General Translation Next.js SDK: getGT URL: https://generaltranslation.com/zh/docs/next/api/strings/get-gt.mdx --- title: getGT description: getGT() 字符串翻译函数 API 参考 --- ## 概述 `getGT` 函数是一个异步函数,用于在构建时翻译字符串。 ```jsx const gt = await getGT();

{ gt('This text will be translated') }

; ``` **构建时翻译:** `getGT` 的翻译发生在构建时,也就是在应用部署之前。 虽然你可以向翻译后的字符串传入变量,但只能翻译在构建时就已知的内容。 ## 参考 ### 参数 无 ### 返回值 一个解析为回调函数 `gt` 的 Promise,该函数会翻译传入的内容。 ```jsx Promise<(content: string, options?: InlineTranslationOptions) => string> ``` | 名称 | 类型 | 描述 | | ---------- | ----------------------------------------------------------------------------- | ------------------- | | `content` | `string` | 待翻译的字符串内容。 | | `options?` | [`InlineTranslationOptions`](/docs/next/api/types/inline-translation-options) | 用于自定义 `gt` 行为的翻译选项。 | *** ## 行为 ### 生产环境 在 CD 过程中,`gt` 函数中的任何内容都会在应用部署前完成翻译。 这可以确保所有区域设置都具备较快的加载速度,但它只能翻译在构建时已知的内容。 翻译生成后,会根据你的配置以两种方式存储: (1) 存储在 CDN 中,或 (2) 存储在应用的构建输出中。 然后,这些翻译后的内容会提供给用户。 如果找不到翻译,则会回退到原始内容。 请务必遵循[此处的部署指南](/docs/next/tutorials/quickdeploy)。 ### 开发 在开发过程中,`gt` 函数会按需翻译内容。 这对快速查看应用在不同语言下的显示效果很有帮助。 请记得在环境变量中添加 Dev API key 以启用此行为。 在开发环境中进行按需翻译时,会出现一定延迟。 在生产构建中不会出现这种情况,除非内容被明确设置为按需翻译, 即使用 [`tx`](/docs/next/api/strings/tx) 或 [``](/docs/next/api/components/tx)。 *** ## 示例 ### 基本用法 你可以使用 `getGT` 翻译字符串。 ```javascript copy import { getGT } from 'gt-next/server'; export default async function TranslateGreeting() { const gt = await getGT(); return (

{gt('Hello, Alice!')}

); } ``` 注意:"Alice" 将被翻译成用户首选的语言。 ### 使用变量 [#variables] 你可以向字典中的翻译传入变量。 ```javascript copy import { getGT } from 'gt-next/server'; export default async function TranslateGreeting() { const gt = await getGT(); return (

{gt('Hello, {name}!', { name: 'Alice' })}

); } ``` 注意:"Alice" 不会被翻译成用户的首选语言,因为它是一个变量。 ### 翻译页面元数据 [#metadata] 在 Next.js 的 `generateMetadata` 中使用 `getGT`,翻译页面标题、说明和 Open Graph 标签。 ```javascript copy import { getGT } from 'gt-next/server'; import { Metadata } from 'next'; export async function generateMetadata(): Promise { const gt = await getGT(); return { title: gt('My App'), description: gt('A fast, modern web application'), openGraph: { title: gt('My App'), description: gt('A fast, modern web application'), }, }; } ``` ### 使用 ICU 消息格式 `gt-next` 支持 ICU 消息格式,因此你也可以对变量进行格式化。 ```javascript copy import { getGT } from 'gt-next/server'; export default async function TranslateGreeting() { const gt = await getGT(); return (

{gt('There are {count, plural, =0 {no items} =1 {one item} other {{count} items}} in the cart', { count: 10 })}

); } ``` ICU 消息格式是一种功能强大的变量格式化方式。 如需了解更多信息,请参阅 [ICU 消息格式文档](https://unicode-org.github.io/icu/userguide/format_parse/messages/)。 *** ## 注意 * `getGT` 函数是一个用于翻译字符串的服务端函数。 * 使用 `getGT` 进行的字符串翻译会在 runtime 之前的构建过程中完成 (开发环境除外) 。 ## 后续步骤 * 如需了解构建时的客户端字符串翻译,请参阅 [`useGT`](/docs/next/api/strings/use-gt)。 * 如需了解 runtime 翻译,请参阅 [`tx`](/docs/next/api/strings/tx) 和 [``](/docs/next/api/components/tx)。