Dictionary
getTranslations()
getTranslations 服务端翻译函数的 API 参考
概述
getTranslations()
用于从翻译字典中获取服务器端组件的字符串翻译。
const d = await getTranslations(); // 获取翻译函数
d('greeting.hello'); // 传递 id 来获取翻译
getTranslations()
支持:
- 字符串和 jsx 内容的翻译。
- 翻译中的变量插入和条件逻辑。
- 可选的 id 前缀。
对于客户端翻译,请参阅 useTranslations()
。
参考
Props
Prop | Type | Default |
---|---|---|
id?? | string | undefined |
描述
Prop | 描述 |
---|---|
id | 一个可选的前缀,用于添加到所有翻译键的前面。这对于处理嵌套字典值很有用。 |
返回值
一个翻译函数 d()
的 promise,给定一个 id,将返回相应条目的翻译版本
Promise<(id: string, options?: DictionaryTranslationOptions) => React.ReactNode>
名称 | 类型 | 描述 |
---|---|---|
id | string | 要翻译的条目的 id |
options? | DictionaryTranslationOptions | 用于自定义 d() 行为的翻译选项。 |
示例
基本用法
字典中的每个条目都会被翻译。
const dictionary = {
greeting: <>Hello, Alice!</>,
};
export default dictionary;
当我们想要访问这些条目时(在服务器端),我们调用 getTranslations()
。
这会返回一个函数,该函数接受字典中翻译的键。
import { getTranslations } from 'gt-next/server';
export default async function TranslateGreeting() {
const d = await getTranslations();
return (
<p>
{d('greeting')} // Hello, Alice // [!code highlight]
</p>
);
}
使用变量
为了传递值,你必须(1)分配一个标识符和(2)在调用 d()
函数时引用该标识符。
在这个示例中,我们使用 {}
向翻译传递变量。
在字典中,我们分配标识符 {userName}
。
const dictionary = {
greeting: "Hello, {userName}!",
};
export default dictionary;
import { getTranslations } from 'gt-next/server';
export default async function TranslateGreeting() {
const d = await getTranslations();
// Hello Alice!
const greetingAlice = d('greeting', { userName: "Alice" });
return (
<p>
{greetingAlice}
</p>
);
}
使用前缀
我们可以使用前缀来只获取字典的一个子集。
const dictionary = {
prefix1: {
prefix2: {
greeting: "Hello, Bob",
}
}
};
export default dictionary;
因为我们在 getTranslations
方法中添加了值 'prefix1.prefix2'
,所有的键都会以 prefix1.prefix2
为前缀:
import { getTranslations } from 'gt-next/server';
export default function UserDetails() {
const d = await getTranslations('prefix1.prefix2');
return (
<div>
<p>{d('greeting')}</p> // greeting => prefix1.prefix2.greeting // [!code highlight]
</div>
);
}
注意事项
getTranslations()
函数允许您在服务器端访问字典翻译。
下一步
- 查看
useTranslations()
了解getTranslations()
的客户端等效方法。 - 在字典参考中了解更多关于使用字典的信息。
这份指南怎么样?