# General Translation Platform: 翻译字符串 URL: https://generaltranslation.com/zh/docs/platform/core/guides/translating-strings.mdx --- title: 翻译字符串 description: 如何使用 generaltranslation 库直接在代码中翻译字符串、批量字符串和结构化内容。 related: links: - /docs/platform/core/guides/translating-files - /docs/platform/core/guides/locale-codes --- 你可以使用 [translate](/docs/platform/core/reference/gt-class-methods/translation/translate) 和 [translateMany](/docs/platform/core/reference/gt-class-methods/translation/translate-many) 直接在代码中翻译字符串。 当你的应用、脚本或服务需要在 Runtime 获取翻译后的内容,而不是翻译整个文件时,请使用字符串翻译。 ## 开始之前 [#before-start] 请先完成 [Quickstart](/docs/platform/core/quickstart),安装 `generaltranslation` 并初始化 [GT](/docs/platform/core/reference/gt-class/constructor) 类。 ## 翻译单个字符串 [#translate-one-string] 调用 [translate](/docs/platform/core/reference/gt-class-methods/translation/translate) 时,传入 source string 和目标区域设置。 如果你的 [GT](/docs/platform/core/reference/gt-class/constructor) 实例设置了 [targetLocale](/docs/platform/core/reference/types/gt-constructor-params),就可以在调用该方法时省略目标区域设置。这在脚本或服务需要将多个字符串翻译到同一个区域设置时很有用。 ```typescript title="src/index.ts" const result = await gt.translate('Hello, world!', 'es'); if (result.success) { console.log(result.translation); // "¡Hola, mundo!" } else { console.error(`Translation failed: ${result.error}`); } ``` 更多信息请参阅 [translate](/docs/platform/core/reference/gt-class-methods/translation/translate) 方法。 ## 批量翻译多个字符串 [#translate-many-strings] 调用 [translateMany](/docs/platform/core/reference/gt-class-methods/translation/translate-many),即可通过一次 API 请求高效翻译多个内容项。它专为批量处理而优化,性能优于多次单独调用 [translate](/docs/platform/core/reference/gt-class-methods/translation/translate)。 ```typescript title="src/index.ts" const results = await gt.translateMany( ['Hello, world!', 'Welcome to our app', 'Click here to continue'], 'es' ); ``` 更多信息请参阅 [translateMany](/docs/platform/core/reference/gt-class-methods/translation/translate-many) 方法。 ## 使用 source 元数据添加上下文 [#add-context-source] 当字符串需要更多上下文时,请使用元数据。 ```typescript title="src/index.ts" const result = await gt.translate( { source: 'Cells', metadata: { context: 'Spreadsheet column header', }, }, 'es' ); ``` 元数据对于含义不明确的词语、UI 标签、产品特定术语,以及在缺少周围上下文时难以理解的字符串都很有帮助。 ## Next steps - /docs/platform/core/guides/translating-files - /docs/platform/core/guides/locale-codes