Part 4

路由与国际化 (i18n)

了解页面与多语言系统在 AstroGlass 中是如何运作的。

AstroGlass 结合了 Astro 基于文件的路由系统以及自定义的国际化 (i18n) 策略。

页面路由

页面存放在 src/pages/ 目录中。文件夹的结构决定了 URL 路径。

对于需要本地化的页面,我们使用单独的目录体系:

  • src/
    • pages/
      • […lang]/ — 动态语言环境路由
        • index.astro — 首页(支持所有语言)
        • [theme].astro — 动态的主题演示页面(例如:/liquid, /zh/glass)
        • [theme]/portfolio.astro — 动态的作品集页面
        • blog/ — 博客页面
        • docs/ — 文档页面
        • privacy.astro — 隐私政策
        • terms.astro — 服务条款
      • 404.astro — /404 错误页
      • about.astro — /about (不进行本地化)

主题演示路由

主题演示页面是通过主题注册表动态生成的。在 src/config/themes.ts 里将某个主题设为 enabled: true 后,系统会自动创建一个路径为 /{themeId} 的路由。

文档路由

文档页面存放在 src/content/docs/[lang]/ 当中:

  • src/
    • content/
      • docs/
        • en/
        • ru/
        • fr/
        • es/
        • ja/
        • zh/
        • kk/

系统会根据文件路径自动生成文档的 URL,例如 /docs/zh/getting-started/introduction

国际化 (i18n)

翻译的处理方式分两种:

  1. 动态页面路由:中心化的 src/pages/[...lang]/ 目录通过 getStaticPaths() 动态处理所有可能的路由组合。
  2. UI 界面字符串:存放于 src/locales/ 目录中的中心化 JSON 文件。

UI 界面级翻译

通用的文本字符串(如导航项、按钮、区块文本等)被存储在按区块分类的 JSON 文件中:

src/locales/
├── en/
├── ru/
├── fr/
├── es/
├── ja/
├── zh/
└── kk/

在组件中使用 useTranslations 函数获取翻译:

Component.astro
---
import { useTranslations } from '../utils/i18n';
import { getLocaleFromUrl } from '../utils/locale-utils';
const locale = getLocaleFromUrl(Astro.url);
const t = useTranslations(locale);
---
<p>{t('hero.title')}</p>
<p>{t('pricing.tier2Name')}</p>

翻译键支持点号表示法用于获取嵌套值。common.json 文件的键在根层级即可调用,而其他文件则根据其文件名限定了命名空间(例如 hero.title, pricing.plans)。

添加新语言

  1. 注册新的区域设置环境

    src/config/locales.ts 中添加带有 enabled: true 的新语言条目。

  2. 创建翻译文件

    创建 src/locales/{code}/ 目录,并添加与英文结构相匹配的 JSON 文件。

  3. 创建文档内容

    src/content/docs/{code}/ 中创建已翻译的 MDX 文件。 (例如:src/content/docs/zh/getting-started/introduction.mdx

  4. 创建博客内容

    src/content/blog/{code}/ 中创建已翻译的 Markdown/MDX 文件。 (例如:src/content/blog/zh/my-post.md

ℹ️
自动探测

i18n 系统使用 Vite 的 import.meta.glob 自动发现 src/locales/ 中的所有 JSON 文件。无需手动导入——只需创建这些文件,它们便可通过 useTranslations() 使用。