快速開始

Astro

本頁示範 Intor 在 Astro 專案中的最小整合流程。


安裝

本範例以 Basic Starter 模板為基礎,建立方式可參考官方文件:Astro

安裝 Intor:

npm install intor
yarn add intor
pnpm add intor
bun add intor

專案結構

index.json
U

index.json
U

Layout.astro
M

index.astro
U

intor-config.ts
U

整合步驟

♯1 翻譯內容

在專案中建立 messages 資料夾,並依語系建立子資料夾,每個語系提供一個 index.json

index.json
U

index.json
U
{
  "hello": "Hello, {name}",
  "rich": "A <tag>text</tag>."
}
{
  "hello": "Bonjour, {name}",
  "rich": "Un <tag>texte</tag>."
}

♯2 設定檔

src/ 下建立 i18n/ 資料夾,並於其中建立 intor-config.ts
本範例採用最基本的翻譯內容載入方式,直接將 messages 定義於設定檔中。

詳見:載入翻譯內容

intor-config.ts
U
import { defineIntorConfig } from "intor";
import EN from "../../messages/en/index.json";
import FR from "../../messages/fr/index.json";

export const intorConfig = defineIntorConfig({
  defaultLocale: "en",
  supportedLocales: ["en", "fr"],
  messages: {
    en: EN,
    fr: FR,
  },
});

♯3 初始化

修改 Layout.astro,讓 <html lang> 可以由外部傳入語系。

Layout.astro
M
---
const { locale } = Astro.props;
---

<!doctype html>
<html lang={locale}>
// ...

pages/ 資料夾中建立 [locale]/,並在底下建立 page.astro

index.astro
U

使用範例

透過 getTranslator 取得翻譯相關能力:

  • t:取得對應文字
  • tRich:渲染包含語意 tag 的結構化翻譯內容
index.astro
U
---
import Layout from "../../layouts/Layout.astro";
import { intorConfig } from "../../i18n/intor-config";
import { getTranslator } from "intor/server";

export async function getStaticPaths() {
  return intorConfig.supportedLocales.map((locale) => ({ params: { locale } }));
}

const { locale } = Astro.params;

const { t, tRich } = await getTranslator(intorConfig, { locale });
---

<Layout locale={locale}>
  <p>{t("hello", { name: "Intor" })}</p>

  <p set:html={tRich("rich", { tag: (children) => `<b>${children}</b>` })} />

  <a href="/en">en</a>
  <a href="/fr">fr</a>
</Layout>

啟動後,前往 http://localhost:4321/en /fr 以預覽結果。