getTranslations
getTranslations 后端(server-side)翻译函数的 API 参考
概览
getTranslations 用于在服务端组件中从 translation dictionary 获取字符串译文。
const d = await getTranslations(); // 获取翻译函数
d('greeting.hello'); // 传入 id 获取对应翻译getTranslations 支持:
- 翻译字符串和 JSX 内容。
- 在翻译中插入变量并编写条件逻辑。
- 可选的 id 前缀。
 
关于客户端翻译,请参见 useTranslations。
getTranslations 和 useTranslations 使用 dictionary 存储全部可翻译内容。
这与使用 <T> 组件 的翻译方式不同。
如果你只打算使用 <T> 组件进行翻译,那么本页内容不适用。
参考资料
属性
Prop
Type
说明
| Prop | 说明 | 
|---|---|
| id | 可选的前缀,将添加到所有翻译键之前。对处理嵌套的字典值很有用。 | 
返回
一个返回翻译函数 d 的 Promise;该函数在给定 id 时,会返回对应条目的译文
Promise<(id: string, options?: DictionaryTranslationOptions) => React.ReactNode>| 名称 | 类型 | 描述 | 
|---|---|---|
| id | string | 要翻译的 Entry 的 id | 
| options? | DictionaryTranslationOptions | 自定义 d行为的 translation options。 | 
示例
字典的基础用法
字典中的每个 Entry 都会被翻译。
const dictionary = {
  greeting: <>你好,Alice!</>, 
};
export default dictionary;当我们需要在服务器端访问这些条目时,调用 getTranslations。
它会返回一个函数,该函数接收字典中某个翻译的键。
import { getTranslations } from 'gt-next/server';
export default async function TranslateGreeting() {
  
  const d = await getTranslations(); 
  return (
    <p>
      {d('greeting')} // 嗨,Alice // [!code highlight]
    </p>
  );
}使用变量
要传递值,你需要 (1) 设定一个标识符,并且 (2) 在调用 d 函数时引用该标识符。
在此示例中,我们使用 {} 向翻译传入变量。
在字典中,我们将标识符设为 {userName}。
const dictionary = {
  greeting: "你好,{userName}!", 
};
export default dictionary;import { getTranslations } from 'gt-next/server';
export default async function TranslateGreeting() {
  const d = await getTranslations();
  
  // 嗨,Alice!
  const greetingAlice = d('greeting', { userName: "Alice" }); 
  return (
    <p>
      {greetingAlice}
    </p>
  );
}使用前缀
我们可以通过前缀仅获取字典的部分内容。
const dictionary = {
  prefix1: { 
    prefix2: { 
      greeting: "嗨,Bob",
    }
  }
};
export default dictionary;因为我们在 getTranslations 方法中传入了 'prefix1.prefix2' 作为 value,因此所有键都会被加上 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的客户端对应方法。
这份指南怎么样?

