Creation:2025-02-07Last update:2025-06-29

    ネスト / サブコンテンツ参照

    ネストの仕組み

    Intlayerでは、nest関数を使用して、別の辞書からコンテンツを参照および再利用することでネストを実現します。コンテンツを重複させる代わりに、キーを使用して既存のコンテンツモジュールを指すことができます。

    ネストの設定

    Intlayerプロジェクトでネストを設定するには、まず再利用したい基本コンテンツを定義します。その後、別のコンテンツモジュールでnest関数を使用してそのコンテンツをインポートします。

    基本辞書

    以下は、別の辞書でネストするための基本辞書の例です:

    firstDictionary.content.ts
    import { type Dictionary } from "intlayer";
    
    const firstDictionary = {
      key: "key_of_my_first_dictionary",
      content: {
        content: "content",
        subContent: {
          contentNumber: 0,
          contentString: "string",
        },
      },
    } satisfies Dictionary;
    
    export default firstDictionary;

    ネストを使用した参照

    次に、上記のコンテンツを参照するためにnest関数を使用する別のコンテンツモジュールを作成します。辞書全体または特定のネストされた値を参照できます:

    secondDictionary.content.ts
    import { nest, type Dictionary } from "intlayer";
    
    const myNestingContent = {
      key: "key_of_my_second_dictionary",
      content: {
        // 辞書全体を参照:
        fullNestedContent: nest("key_of_my_first_dictionary"),
        // 特定のネストされた値を参照:
        partialNestedContent: nest(
          "key_of_my_first_dictionary",
          "subContent.contentNumber"
        ),
      },
    } satisfies Dictionary;
    
    export default myNestingContent;

    第2引数として、そのコンテンツ内のネストされた値へのパスを指定できます。パスが指定されていない場合、参照された辞書の全コンテンツが返されます。

    React Intlayerでのネストの使用

    Reactコンポーネントでネストされたコンテンツを使用するには、react-intlayerパッケージのuseIntlayerフックを活用します。このフックは、指定されたキーに基づいて正しいコンテンツを取得します。以下はその使用例です:

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const NestComponent: FC = () => {
      const { fullNestedContent, partialNestedContent } = useIntlayer(
        "key_of_my_second_dictionary"
      );
    
      return (
        <div>
          <p>
            Full Nested Content: {JSON.stringify(fullNestedContent)}
            {/* 出力: {"content": "content", "subContent": {"contentNumber": 0, "contentString": "string"}} */}
          </p>
          <p>
            Partial Nested Value: {partialNestedContent}
            {/* 出力: 0 */}
          </p>
        </div>
      );
    };
    
    export default NestComponent;

    追加リソース

    設定や使用方法の詳細については、以下のリソースを参照してください:

    これらのリソースは、さまざまな環境やフレームワークでのIntlayerのセットアップと使用方法についてさらに詳しく説明しています。