Автор:
    Дата створення:2025-08-23Останнє оновлення:2025-08-23

    Перелічення / Утворення множини

    Як працює перелічення

    В Intlayer перелічення реалізується за допомогою функції enu, яка зіставляє конкретні ключі з відповідним вмістом. Ці ключі можуть представляти числові значення, діапазони або власні ідентифікатори. При використанні з React Intlayer або Next Intlayer відповідний вміст автоматично вибирається на основі локалі застосунку та визначених правил.

    Налаштування перерахувань

    Щоб налаштувати перерахування у вашому проєкті Intlayer, потрібно створити модуль контенту, який містить визначення перерахувань. Ось приклад простого перерахування для кількості автомобілів:

    **/*.content.ts
    import { enu, type Dictionary } from "intlayer";
    
    const carEnumeration = {
      key: "car_count",
      content: {
        numberOfCar: enu({
          "<-1": "Менше ніж -1 автомобіля",
          "-1": "Мінус один автомобіль",
          "0": "Жодних автомобілів",
          "1": "Один автомобіль",
          ">5": "Кілька автомобілів",
          ">19": "Багато автомобілів",
          "fallback": "Значення за замовчуванням", // Необов'язково
        }),
      },
    } satisfies Dictionary;
    
    export default carEnumeration;
    

    У цьому прикладі enu відображає різні умови на конкретний вміст. При використанні в React-компоненті Intlayer може автоматично вибирати відповідний вміст на основі заданої змінної.

    Порядок оголошення має значення в перерахуваннях Intlayer. Перше допустиме оголошення, те, яке буде обрано. Якщо застосовуються кілька умов, упевніться, що вони розташовані в правильному порядку, щоб уникнути непередбачуваної поведінки.
    Якщо не вказано fallback, функція поверне undefined, якщо жоден ключ не підходить.

    Використання перерахувань з React Intlayer

    To use enumeration in a React component, you can leverage the useIntlayer hook from the react-intlayer package. This hook retrieves the correct content based on the specified ID. Here's an example of how to use it:

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const CarComponent: FC = () => {
      const { numberOfCar } = useIntlayer("car_count");
    
      return (
        <div>
          <p>
            {
              numberOfCar(0) // Output: No cars
            }
          </p>
          <p>
            {
              numberOfCar(6) // Output: Some cars
            }
          </p>
          <p>
            {
              numberOfCar(20) // Output: Many cars
            }
          </p>
          <p>
            {
              numberOfCar(0.01) // Output: Fallback value
            }
          </p>
        </div>
      );
    };
    

    To use enumeration in Next.js Client Components, retrieve it via the useIntlayer hook. Here's an example:

    **/*.tsx
    "use client";
    
    import type { FC } from "react";
    import { useIntlayer } from "next-intlayer";
    
    const CarComponent: FC = () => {
      const { numberOfCar } = useIntlayer("car_count");
    
      return (
        <div>
          <p>{numberOfCar(6)}</p>
        </div>
      );
    };
    
    export default CarComponent;
    

    To use enumeration in Vue components, retrieve it via the useIntlayer hook. Here's an example:

    **/*.vue
    <script setup lang="ts">
    import { useIntlayer } from "vue-intlayer";
    
    const { numberOfCar } = useIntlayer("car_count");
    </script>
    
    <template>
      <div>
        <p>{{ numberOfCar(6) }}</p>
      </div>
    </template>
    

    To use enumeration in Svelte components, retrieve it via the useIntlayer hook. The store is accessed with $. Here's an example:

    **/*.svelte
    <script lang="ts">
    import { useIntlayer } from "svelte-intlayer";
    
    const content = useIntlayer("car_count");
    </script>
    
    <div>
      <p>{$content.numberOfCar(6)}</p>
    </div>
    

    To use enumeration in Preact components, retrieve it via the useIntlayer hook. Here's an example:

    **/*.tsx
    import type { FC } from "preact";
    import { useIntlayer } from "preact-intlayer";
    
    const CarComponent: FC = () => {
      const { numberOfCar } = useIntlayer("car_count");
    
      return (
        <div>
          <p>{numberOfCar(6)}</p>
        </div>
      );
    };
    
    export default CarComponent;
    

    To use enumeration in SolidJS components, retrieve it via the useIntlayer hook. Here's an example:

    **/*.tsx
    import type { Component } from "solid-js";
    import { useIntlayer } from "solid-intlayer";
    
    const CarComponent: Component = () => {
      const { numberOfCar } = useIntlayer("car_count");
    
      return (
        <div>
          <p>{numberOfCar(6)}</p>
        </div>
      );
    };
    
    export default CarComponent;
    

    To use enumeration in Angular components, retrieve it via the useIntlayer hook. Here's an example:

    app.component.ts
    import { Component } from "@angular/core";
    import { useIntlayer } from "angular-intlayer";
    
    @Component({
      selector: "app-car",
      template: `
        <div>
          <p>{{ content().numberOfCar(6) }}</p>
        </div>
      `,
    })
    export class CarComponent {
      content = useIntlayer("car_count");
    }
    

    To use enumeration with vanilla-intlayer, retrieve it via the useIntlayer hook. Here's an example:

    **/*.ts
    import { installIntlayer, useIntlayer } from "vanilla-intlayer";
    
    installIntlayer();
    
    const content = useIntlayer("car_count").onChange((newContent) => {
      document.getElementById("cars")!.textContent = newContent.numberOfCar(6);
    });
    
    // Initial render
    document.getElementById("cars")!.textContent = content.numberOfCar(6);
    

    Додаткові ресурси

    Для детальнішої інформації про налаштування та використання зверніться до наступних ресурсів:

    Ці ресурси надають додаткову інформацію про налаштування та використання Intlayer в різних середовищах і з різними фреймворками.

    Using Ordinal Enumeration

    To use this in a React component, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const RankingComponent: FC<{ count: number }> = ({ count }) => {
      const { ordinal } = useIntlayer("ranking_component");
    
      // Get the last digit to determine the correct suffix
      const lastDigit = Math.abs(count) % 10;
    
      return (
        <div>
          <p>
            {
              ordinal(lastDigit)({ count }) // e.g., "5th place" for count=5
            }
          </p>
        </div>
      );
    };
    

    To use this in Next.js Client Components, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.tsx
    "use client";
    
    import type { FC } from "react";
    import { useIntlayer } from "next-intlayer";
    
    const RankingComponent: FC<{ count: number }> = ({ count }) => {
      const { ordinal } = useIntlayer("ranking_component");
      const lastDigit = Math.abs(count) % 10;
    
      return (
        <div>
          <p>{ordinal(lastDigit)({ count })}</p>
        </div>
      );
    };
    
    export default RankingComponent;
    

    To use this in Vue components, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.vue
    <script setup lang="ts">
    import { useIntlayer } from "vue-intlayer";
    
    defineProps<{ count: number }>();
    
    const { ordinal } = useIntlayer("ranking_component");
    </script>
    
    <template>
      <div>
        <p>{{ ordinal(Math.abs(count) % 10)({ count }) }}</p>
      </div>
    </template>
    

    To use this in Svelte components, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.svelte
    <script lang="ts">
    import { useIntlayer } from "svelte-intlayer";
    
    export let count: number;
    
    const content = useIntlayer("ranking_component");
    $: lastDigit = Math.abs(count) % 10;
    </script>
    
    <div>
      <p>{$content.ordinal(lastDigit)({ count })}</p>
    </div>
    

    To use this in Preact components, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.tsx
    import type { FC } from "preact";
    import { useIntlayer } from "preact-intlayer";
    
    const RankingComponent: FC<{ count: number }> = ({ count }) => {
      const { ordinal } = useIntlayer("ranking_component");
      const lastDigit = Math.abs(count) % 10;
    
      return (
        <div>
          <p>{ordinal(lastDigit)({ count })}</p>
        </div>
      );
    };
    
    export default RankingComponent;
    

    To use this in SolidJS components, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.tsx
    import type { Component } from "solid-js";
    import { useIntlayer } from "solid-intlayer";
    
    const RankingComponent: Component<{ count: number }> = (props) => {
      const { ordinal } = useIntlayer("ranking_component");
    
      return (
        <div>
          <p>{ordinal(Math.abs(props.count) % 10)({ count: props.count })}</p>
        </div>
      );
    };
    
    export default RankingComponent;
    

    To use this in Angular components, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    app.component.ts
    import { Component, Input } from "@angular/core";
    import { useIntlayer } from "angular-intlayer";
    
    @Component({
      selector: "app-ranking",
      template: `
        <div>
          <p>{{ content().ordinal(lastDigit())({ count }) }}</p>
        </div>
      `,
    })
    export class RankingComponent {
      @Input() count!: number;
    
      content = useIntlayer("ranking_component");
    
      lastDigit() {
        return Math.abs(this.count) % 10;
      }
    }
    

    To use this with vanilla-intlayer, call the enumeration with the last digit of the number to get the correct suffix, then pass the full count as the insertion value:

    **/*.ts
    import { installIntlayer, useIntlayer } from "vanilla-intlayer";
    
    installIntlayer();
    
    const content = useIntlayer("ranking_component");
    const lastDigit = Math.abs(5) % 10;
    
    document.getElementById("ranking")!.textContent = content.ordinal(lastDigit)({
      count: 5,
    });
    

    Additional Resources

    For more detailed information on configuration and usage, refer to the following resources:

    These resources provide further insights into the setup and usage of Intlayer in different environments and with various frameworks.