Đặt câu hỏi và nhận tóm tắt tài liệu bằng cách tham chiếu trang này và nhà cung cấp AI bạn chọn
Bằng cách tích hợp Intlayer MCP Server vào trợ lý AI ưa thích của bạn, bạn có thể truy xuất toàn bộ tài liệu trực tiếp từ ChatGPT, DeepSeek, Cursor, VSCode, v.v.
Xem tài liệu MCP ServerNội dung của trang này đã được dịch bằng AI.
Xem phiên bản mới nhất của nội dung gốc bằng tiếng AnhNếu bạn có ý tưởng để cải thiện tài liệu này, vui lòng đóng góp bằng cách gửi pull request trên GitHub.
Liên kết GitHub tới tài liệuSao chép Markdown của tài liệu vào bộ nhớ tạm
Translation
Defining Translations
The t function in intlayer allows you to declare content in multiple languages. This function ensures type safety, raising an error if any translations are missing, which is particularly useful in TypeScript environments.
Here's an example of how to declare content with translations.
Sao chép đoạn mã vào khay nhớ tạm (clipboard)
import { t, type Dictionary } from "intlayer";interface Content { welcomeMessage: string;}export default { key: "multi_lang", content: { welcomeMessage: t({ en: "Welcome to our application", fr: "Bienvenue dans notre application", es: "Bienvenido a nuestra aplicación", }), },} satisfies Dictionary<Content>;Configuration for Locales
To ensure proper translation handling, you can configure the accepted locales in intlayer.config.ts. This configuration allows you to define the languages that your application supports:
Sao chép đoạn mã vào khay nhớ tạm (clipboard)
import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { internationalization: { locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH], },};export default config;Using Translations in React Components
With react-intlayer, you can use translations in React components. Here's an example:
Sao chép đoạn mã vào khay nhớ tạm (clipboard)
import type { FC } from "react";import { useIntlayer } from "react-intlayer";const MyComponent: FC = () => { const content = useIntlayer("multi_lang"); return ( <div> <p>{content.welcomeMessage}</p> </div> );};export default MyComponent;This component fetches the corresponding translation based on the current locale set in your application.
Custom Content Objects
intlayer supports custom content objects for translation, allowing you to define more complex structures while ensuring type safety. Here's an example with a custom object:
Sao chép đoạn mã vào khay nhớ tạm (clipboard)
import { t, type Dictionary } from "intlayer";interface ICustomContent { title: string; content: string;}const customContent = { key: "custom_content", content: { profileText: t<ICustomContent>({ en: { title: "Page Title", content: "Page Content", }, fr: { title: "Titre de la Page", content: "Contenu de la Page", }, es: { title: "Título de la Página", content: "Contenido de la Página", }, }), },} satisfies Dictionary;export default customContent;