intlayer-content

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Intlayer Content Nodes

Intlayer内容节点

Define rich and dynamic content using Intlayer functions. Use the reference below for each node type.
使用Intlayer函数定义丰富的动态内容。以下是各节点类型的参考说明。

Translation (
t
)

翻译(
t

Define multilingual content mapped to locales.
Doc
typescript
import { t } from "intlayer";

const content = t({
  en: "Hello",
  fr: "Bonjour",
  es: "Hola",
});
Find locales to declare in config file. Supported configuration files:
  • intlayer.config.{ts|js|json|json5|jsonc|cjs|mjs}
  • .intlayerrc
定义与语言环境映射的多语言内容。
文档
typescript
import { t } from "intlayer";

const content = t({
  en: "Hello",
  fr: "Bonjour",
  es: "Hola",
});
可在配置文件中声明语言环境。支持的配置文件:
  • intlayer.config.{ts|js|json|json5|jsonc|cjs|mjs}
  • .intlayerrc

Enumeration (
enu
)

枚举(
enu

Map content to specific keys, numbers, or ranges (useful for pluralization).
Doc
typescript
import { enu } from "intlayer";

const carCount = enu({
  "0": "No cars",
  "1": "One car",
  ">1": "Multiple cars",
  fallback: "Unknown amount",
});
将内容映射到特定键、数字或范围(适用于复数处理场景)。
文档
typescript
import { enu } from "intlayer";

const carCount = enu({
  "0": "No cars",
  "1": "One car",
  ">1": "Multiple cars",
  fallback: "Unknown amount",
});

Condition (
cond
)

条件(
cond

Define content based on a boolean condition.
Doc
typescript
import { cond } from "intlayer";

const isLoggedIn = cond({
  true: "Welcome back!",
  false: "Please log in",
  fallback: "Status unknown", // Optional
});
基于布尔条件定义内容。
文档
typescript
import { cond } from "intlayer";

const isLoggedIn = cond({
  true: "Welcome back!",
  false: "Please log in",
  fallback: "Status unknown", // 可选
});

Markdown (
md
)

Markdown(
md

Define rich text using Markdown syntax.
Doc
typescript
import { md } from "intlayer";

const article = md("# Title\n\nSome **bold** text.");
使用Markdown语法定义富文本内容。
文档
typescript
import { md } from "intlayer";

const article = md("# Title\n\nSome **bold** text.");

HTML (
html
)

HTML(
html

Define HTML content, optionally with custom components.
Doc
typescript
import { html } from "intlayer";

const richText = html("<p>Hello <strong>World</strong></p>");
定义HTML内容,可选择搭配自定义组件。
文档
typescript
import { html } from "intlayer";

const richText = html("<p>Hello <strong>World</strong></p>");

Nesting (
nest
)

嵌套引用(
nest

Reuse content from another dictionary.
Doc
typescript
import { nest } from "intlayer";

// Reference entire dictionary
const fullRef = nest("other_dictionary_key");

// Reference specific path
const partialRef = nest("other_dictionary_key", "path.to.value");
复用其他字典中的内容。
文档
typescript
import { nest } from "intlayer";

// 引用整个字典
const fullRef = nest("other_dictionary_key");

// 引用特定路径
const partialRef = nest("other_dictionary_key", "path.to.value");

Function Fetching

函数获取内容

Execute logic to generate content (synchronous or asynchronous).
Doc
typescript
const computed = () => `Current time: ${new Date().toISOString()}`;

const fetched = async () => {
  const data = await fetch("/api/data").then((res) => res.json());
  return data.message;
};
执行逻辑生成内容(同步或异步)。
文档
typescript
const computed = () => `Current time: ${new Date().toISOString()}`;

const fetched = async () => {
  const data = await fetch("/api/data").then((res) => res.json());
  return data.message;
};

Insertion (
insert
)

变量插入(
insert

Define dynamic content with variables.
Doc
typescript
import { insert } from "intlayer";

const welcome = insert("Hello {{name}}!");
定义包含变量的动态内容。
文档
typescript
import { insert } from "intlayer";

const welcome = insert("Hello {{name}}!");

File (
file
)

文件引用(
file

Reference external files as content.
Doc
typescript
import { file } from "intlayer";

const myFile = file("./path/to/file.txt");
引用外部文件作为内容。
文档
typescript
import { file } from "intlayer";

const myFile = file("./path/to/file.txt");

Gender (
gender
)

性别适配(
gender

Define content based on gender ('male', 'female', etc.).
Doc
typescript
import { gender } from "intlayer";

const greeting = gender({
  male: "Welcome sir",
  female: "Welcome madam",
  fallback: "Welcome",
});
基于性别('male'、'female'等)定义内容。
文档
typescript
import { gender } from "intlayer";

const greeting = gender({
  male: "Welcome sir",
  female: "Welcome madam",
  fallback: "Welcome",
});

Example Directory Structure (react)

React项目示例目录结构

src/
├── components/
│   ├── MyComponent/
│   │   ├── index.content.ts          # Content declaration
│   │   └── index.tsx                 # Component
│   ├── myOtherComponent.content.ts   # Content declaration
│   └── MyOtherComponent.tsx          # Component
src/
├── components/
│   ├── MyComponent/
│   │   ├── index.content.ts          # 内容声明文件
│   │   └── index.tsx                 # 组件文件
│   ├── myOtherComponent.content.ts   # 内容声明文件
│   └── MyOtherComponent.tsx          # 组件文件

Content Templates

内容模板

TypeScript (.content.ts)
typescript
import { t, type Dictionary } from "intlayer";

const content = {
  key: "my-component-key",
  content: {
    title: "...",
  },
} satisfies Dictionary;

export default content;
TypeScript with React (.content.tsx)
tsx
import { t, type Dictionary } from "intlayer";
import { ReactNode } from "react";

const content = {
  key: "my-component-key",
  content: {
    title: <>My React Node</>,
  },
} satisfies Dictionary;

export default content;
json
{
  "key": "my-component-key",
  "content": {
    "title": "..."
  }
}
javascript
import { t } from "intlayer";

/** @type {import('intlayer').Dictionary} **/
const content = {
  key: "my-component-key",
  content: {
    title: "...",
  },
};

export default content;
TypeScript (.content.ts)
typescript
import { t, type Dictionary } from "intlayer";

const content = {
  key: "my-component-key",
  content: {
    title: "...",
  },
} satisfies Dictionary;

export default content;
TypeScript + React (.content.tsx)
tsx
import { t, type Dictionary } from "intlayer";
import { ReactNode } from "react";

const content = {
  key: "my-component-key",
  content: {
    title: <>My React Node</>,
  },
} satisfies Dictionary;

export default content;
json
{
  "key": "my-component-key",
  "content": {
    "title": "..."
  }
}
javascript
import { t } from "intlayer";

/** @type {import('intlayer').Dictionary} **/
const content = {
  key: "my-component-key",
  content: {
    title: "...",
  },
};

export default content;

Content declaration combination

内容声明组合

Nodes can be imbricated for complex logic.
tsx
import {
  cond,
  enu,
  file,
  gender,
  insert,
  html,
  md,
  nest,
  t,
  type Dictionary,
} from "intlayer";

const content = {
  key: "test",
  title: "Test component content",
  description:
    "Content declarations for the Test component, including examples of plurals, conditions, gender-specific messages, dynamic insertions, markdown, file-based content and nested dictionaries used for demonstration and testing purposes.",
  content: {
    baseContent: "Intlayer", // Content that no need to be i18n
    welcomeMessage: t({
      en: "Welcome to our application",
      "en-GB": "Welcome to our application",
      fr: "Bienvenue dans notre application",
      es: "Bienvenido a nuestra aplicación",
      // ... All other locales set in intlayer config file
    }),
    numberOfCar: enu({
      // Check all conditions in other
      "<-1": "Less than minus one car",
      "-1": "Minus one car",
      "0": "No cars",
      "1": "One car",
      ">19": "Many cars",
      ">5": "Some cars", // Will never will triggered, because >5 is included between 1 and >19
      fallback: "Fallback value", // Optional but avoid undefined type
    }),
    myCondition: cond({
      true: "my content when it's true",
      false: "my content when it's false",
      fallback: "my content when the condition fails", // Optional but avoid undefined type
    }),
    myGender: gender({
      male: "my content for male users",
      female: "my content for female users",
      fallback: "my content when gender is not specified", // Optional but avoid undefined type
    }),
    myInsertion: insert(
      "Hello, my name is {{name}} and I am {{age}} years old!"
    ),
    myMultilingualInsertion: insert(
      t({
        ar: "مرحبا, اسمي {{name}} وأنا {{age}} سنة!",
        de: "Hallo, mein Name ist {{name}} und ich bin {{age}} Jahre alt!",
        en: "Hello, my name is {{name}} and I am {{age}} years old!",
        "en-GB": "Hello, my name is {{name}} and I am {{age}} years old!",
      })
    ),
    myTextFile: file("./test.txt"), // File helps to know where is located the file
    subContent: {
      contentNumber: 0,
      contentString: "string",
    },
    fullNested: nest("code"),
    // References a specific nested value:
    partialNested: nest("code", "title"),
    myMarkdown: md("## My title \n\nLorem Ipsum"),
    myMarkdownFile: md(file("./test.md")),
    multilingualMarkdown: t({
      en: md("## test en"),
      fr: md("## test fr"),
      es: md("## test es"),
      "en-GB": md("## test en-GB"),
    }),
    myHTML: html("<h2>My title</h2><p>Lorem Ipsum</p>"),
    myHTMLFile: html(file("./test.html")),

    arrayContent: ["string", "string2", "string3"],
    arrayOfObject: [
      {
        name: "item1",
        description: "description1",
      },
      {
        name: "item2",
        description: "description2",
      },
    ],
    objectOfArray: {
      array: ["item1", "item2", "item3"],
      object: {
        name: "object name",
        description: "object description",
      },
    },
  },
  tags: ["test", "test page"],
} satisfies Dictionary;

export default content;
节点可以嵌套使用以实现复杂逻辑。
tsx
import {
  cond,
  enu,
  file,
  gender,
  insert,
  html,
  md,
  nest,
  t,
  type Dictionary,
} from "intlayer";

const content = {
  key: "test",
  title: "Test component content",
  description:
    "Content declarations for the Test component, including examples of plurals, conditions, gender-specific messages, dynamic insertions, markdown, file-based content and nested dictionaries used for demonstration and testing purposes.",
  content: {
    baseContent: "Intlayer", // 无需国际化的内容
    welcomeMessage: t({
      en: "Welcome to our application",
      "en-GB": "Welcome to our application",
      fr: "Bienvenue dans notre application",
      es: "Bienvenido a nuestra aplicación",
      // ... 所有其他在intlayer配置文件中设置的语言环境
    }),
    numberOfCar: enu({
      // 检查所有其他条件
      "<-1": "Less than minus one car",
      "-1": "Minus one car",
      "0": "No cars",
      "1": "One car",
      ">19": "Many cars",
      ">5": "Some cars", // 不会被触发,因为>5包含在1到>19之间
      fallback: "Fallback value", // 可选,但可避免undefined类型
    }),
    myCondition: cond({
      true: "my content when it's true",
      false: "my content when it's false",
      fallback: "my content when the condition fails", // 可选,但可避免undefined类型
    }),
    myGender: gender({
      male: "my content for male users",
      female: "my content for female users",
      fallback: "my content when gender is not specified", // 可选,但可避免undefined类型
    }),
    myInsertion: insert(
      "Hello, my name is {{name}} and I am {{age}} years old!"
    ),
    myMultilingualInsertion: insert(
      t({
        ar: "مرحبا, اسمي {{name}} وأنا {{age}} سنة!",
        de: "Hallo, mein Name ist {{name}} und ich bin {{age}} Jahre alt!",
        en: "Hello, my name is {{name}} and I am {{age}} years old!",
        "en-GB": "Hello, my name is {{name}} and I am {{age}} years old!",
      })
    ),
    myTextFile: file("./test.txt"), // File函数用于指定文件位置
    subContent: {
      contentNumber: 0,
      contentString: "string",
    },
    fullNested: nest("code"),
    // 引用特定的嵌套值:
    partialNested: nest("code", "title"),
    myMarkdown: md("## My title \n\nLorem Ipsum"),
    myMarkdownFile: md(file("./test.md")),
    multilingualMarkdown: t({
      en: md("## test en"),
      fr: md("## test fr"),
      es: md("## test es"),
      "en-GB": md("## test en-GB"),
    }),
    myHTML: html("<h2>My title</h2><p>Lorem Ipsum</p>"),
    myHTMLFile: html(file("./test.html")),

    arrayContent: ["string", "string2", "string3"],
    arrayOfObject: [
      {
        name: "item1",
        description: "description1",
      },
      {
        name: "item2",
        description: "description2",
      },
    ],
    objectOfArray: {
      array: ["item1", "item2", "item3"],
      object: {
        name: "object name",
        description: "object description",
      },
    },
  },
  tags: ["test", "test page"],
} satisfies Dictionary;

export default content;

Type validation of dictionary

字典类型验证

ts
Dictionary<{ title: string; description?: string }>; // Generic describing content type for formatted data (metadata, etc)
ts
Dictionary<{ title: string; description?: string }>; // 用于描述格式化数据(元数据等)的泛型

Key Dictionary Fields for AI Management

AI管理的核心字典字段

核心元数据

Core Metadata
  • key: The identifier for the dictionary (e.g.,
    about-page-meta
    ). AI can ensure consistent naming conventions.
  • title: A human-readable name for identification in the CMS or editor.
  • description: Provides context for the dictionary. AI uses this to understand the purpose and generate better translations or content.
  • tags: Categorization strings (e.g.,
    metadata
    ,
    SEO
    ) to help organize and filter dictionaries.
Content & Localization
  • locale: Specifies the language of the content for (per-locale file)[references/concept_per-locale-file.md]
  • contentAutoTransformation: A toggle to automatically convert raw strings into specialized formats like Markdown, HTML, or Insertions (variables).
  • fill: An instruction indicating whether the dictionary should be automatically populated by AI/automation tools.
Behaviorals Settings
  • priority: A numeric value used to resolve conflicts during merge of dictionaries under a same key.
  • importMode: Defines how content is loaded (
    static
    ,
    dynamic
    , or
    live
    ). AI can recommend the best mode based on performance needs.
  • location: Controls CMS synchronization (
    hybrid
    ,
    remote
    ,
    local
    ). AI can manage where the source of truth resides.
  • schema: string that use zod schema declared in config file to validate data
  • key:字典的唯一标识(例如
    about-page-meta
    )。AI可确保命名规则的一致性。
  • title:用于在CMS或编辑器中识别的可读名称。
  • description:提供字典的上下文信息。AI会利用此信息理解其用途,从而生成更优质的翻译或内容。
  • tags:分类字符串(例如
    metadata
    SEO
    ),用于帮助组织和筛选字典。

References

内容与国际化

  • Content Overview
  • Exports intlayer package
  • locale:指定内容的语言(适用于单语言文件
  • contentAutoTransformation:开关选项,用于自动将原始字符串转换为Markdown、HTML或变量插入(Insertions)等特殊格式。
  • fill:指示是否应通过AI/自动化工具自动填充字典内容的指令。

行为设置

  • priority:数值类型,用于解决相同键名下多个字典合并时的冲突。
  • importMode:定义内容的加载方式(
    static
    dynamic
    live
    )。AI可根据性能需求推荐最佳模式。
  • location:控制CMS同步方式(
    hybrid
    remote
    local
    )。AI可管理内容源的存储位置。
  • schema:字符串类型,使用配置文件中声明的zod schema验证数据。

参考链接

  • 内容概述
  • Intlayer包导出内容