tx
tx 字符串翻译函数 API 参考
概览
tx 函数是一种用于翻译字符串的 server-side 函数。
await tx('Hello, world!'); // 返回 'Hola, mundo!'运行时翻译:
tx 翻译在运行时执行。
这意味着翻译会实时进行,因此你可以翻译运行时可用的内容。
参考
参数
Prop
Type
| 名称 | 描述 |
|---|---|
content | 需要翻译的字符串。 |
options | 用于自定义 tx 行为的翻译选项。参见 RuntimeTranslationOptions。 |
返回值
一个 Promise,解析为包含翻译后内容的字符串;如果无需翻译,则为原始内容。
运行机制
tx 函数会在运行时翻译字符串。
这意味着翻译是实时执行的,因此你可以翻译仅在运行时才可得的内容。
权衡在于:由于需要等待按需翻译加载,速度会明显变慢。
我们建议尽可能在构建阶段使用 getGT、useGT 或 <T> 进行翻译,
仅在必要时才使用按需翻译,例如 tx 和 <Tx>。
请务必遵循此部署指南。
示例
基本用法
可以使用 tx 来翻译字符串。
import { tx } from 'gt-next/server';
export default async function translateGreeting() {
return await tx("你好,世界!");
}添加上下文
你可以通过提供翻译时需要参考的上下文来定制译文。
import { tx } from 'gt-next/server';
export default async function TranslateWithOptions() {
return await tx("Hello, world!", {
$context: '使用非正式语气翻译'
});
}使用变量
要向字符串传递值,你需要 (1) 赋予一个标识符,并 (2) 在传入的对象中引用该标识符。
import { tx } from 'gt-next/server';
export default async function translateWithVariables() {
return await tx("费用为 {price, number, ::currency/USD}", {
price: 29.99,
});
}指定 locale
你可以指定用于翻译的 locale。 默认情况下,locale 将设为用户的首选语言。
import { tx } from 'gt-next/server';
export default async function translateWithLocale() {
return await tx("你好,世界!", { $locale: 'fr' });
}注意事项
tx仅限于服务端使用,不能在客户端组件中使用。- 使用
tx的翻译发生在运行时,也就是即时翻译。这比构建时翻译要慢得多。
下一步
- 请参见
useGT和getGT,了解如何在部署前翻译字符串。 - 若需翻译 JSX,请参见
<T>和<Tx>。 - 关于自定义翻译的更多信息,请参见
RuntimeTranslationOptions。
本指南如何?