Dictionary

getDict()

getDict サーバーサイド翻訳関数の API リファレンス

概要

getDict() は、サーバーサイドコンポーネント用の翻訳辞書から文字列の翻訳を取得するために使用されます。

const d = await getDict(); // 翻訳関数を取得
d('greeting.hello'); // idを渡して翻訳を取得

getDict() は以下をサポートします:

  • 文字列およびjsxコンテンツの翻訳。
  • 翻訳内での変数挿入と条件ロジック。
  • オプションのidプレフィックス。

クライアントサイドの翻訳については、useDict()を参照してください。

getDict()useDict() は、翻訳のためのすべてのコンテンツを保存するために辞書を使用します。 これは、翻訳のために<T> コンポーネントを使用することとは異なります。 翻訳に <T> コンポーネントのみを使用することに興味がある場合、このドキュメントは関連しません。

リファレンス

Props

PropTypeDefault
id??
string
undefined

説明

Prop説明
idすべての翻訳キーに追加するためのオプションのプレフィックスです。これはネストされた辞書の値を扱うのに便利です。

戻り値

d() という翻訳関数のプロミスで、id を与えると、対応するエントリの翻訳版を返します

Promise<(id: string, options?: DictionaryTranslationOptions) => React.ReactNode>
名前説明
idstring翻訳されるエントリの id
options?DictionaryTranslationOptionsd() の動作をカスタマイズするための翻訳オプション。

基本的な使い方

辞書内のすべてのエントリが翻訳されます。

dictionary.jsx
const dictionary = {
  greeting: <>Hello, Alice!</>, 
};
export default dictionary;

これらのエントリにアクセスしたいとき(サーバーサイドで)、getDict() を呼び出します。 これは、辞書から翻訳のキーを受け取る関数を返します。

TranslateGreeting.jsx
import { getDict } from 'gt-next/server';
 
export default async function TranslateGreeting() {
  
  const d = await getDict(); 
 
  return (
    <p>
      {d('greeting')} // Hello, Alice // [!code highlight]
    </p>
  );
}

変数の使用

値を渡すためには、(1)識別子を割り当て、(2)d() 関数を呼び出すときに識別子を参照する必要があります。

この例では、{} を使用して翻訳に変数を渡します。 辞書では、識別子 {userName} を割り当てます。

dictionary.jsx
const dictionary = {
  greeting: "Hello, {userName}!", 
};
export default dictionary;
TranslateGreeting.jsx
import { getDict } from 'gt-next/server';
 
export default async function TranslateGreeting() {
  const d = await getDict();
  
  // Hello Alice!
  const greetingAlice = d('greeting', { userName: "Alice" }); 
 
  return (
    <p>
      {greetingAlice}
    </p>
  );
}

プレフィックスの使用

プレフィックスを使用して、辞書のサブセットのみを取得できます。

dictionary.jsx
const dictionary = {
  prefix1: { 
    prefix2: { 
      greeting: "Hello, Bob",
    }
  }
};
export default dictionary;

getDict メソッドに 'prefix1.prefix2' の値を追加したため、すべてのキーは prefix1.prefix2 でプレフィックスされます:

UserDetails.jsx
import { getDict } from 'gt-next/server';
 
export default function UserDetails() {
  const d = await getDict('prefix1.prefix2'); 
  return (
    <div>
      <p>{d('greeting')}</p> // greeting => prefix1.prefix2.greeting // [!code highlight]
    </div>
  );
}

メモ

  • getDict() 関数は、サーバー側で辞書の翻訳にアクセスすることを可能にします。

次のステップ

  • getDict() のクライアントサイドの同等機能については、useDict() を参照してください。
  • 辞書の使用方法については、辞書リファレンス を参照してください。

このページについて