logo
0
0
WeChat Login
cnb<cnb@example.com>
2026033101

中英文双语网站配置说明

本项目已配置为支持中英文双语的电商网站。以下是配置的详细说明和使用指南。

配置结构

1. 语言配置文件

src/i18n/locales.ts - 包含所有翻译内容和语言配置:

// 语言配置 export const locales = { en: { name: 'English', code: 'en' }, zh: { name: '中文', code: 'zh' } }; // 翻译内容 export const translations = { en: { // 英语翻译 home: 'Home', computers: 'Computers', // ... }, zh: { // 中文翻译 home: '首页', computers: '电脑', // ... } };

2. i18n 辅助函数

src/i18n/useI18n.ts - 提供获取当前语言和翻译内容的函数:

export function useI18n(astro: AstroGlobal | APIContext) { const locale = getCurrentLocale(astro); const t = (key: string): string => { return translations[locale][key] || key; }; return { locale, t }; }

3. 语言切换组件

src/components/ui/LanguageSwitcher.astro - 允许用户在中英文之间切换:

<div class="dropdown dropdown-end"> <div tabindex="0" role="button"> {locales[currentLocale].name} </div> <ul class="dropdown-content"> {Object.entries(locales).map(([code, locale]) => ( <li> <a href={code === defaultLocale ? '/' : `/${code}`}> {locale.name} </a> </li> ))} </ul> </div>

4. Astro 配置

astro.config.mjs - 配置国际化路由和默认语言:

export default defineConfig({ i18n: { defaultLocale: 'en', locales: ['en', 'zh'], routing: { prefixDefaultLocale: false, redirectToDefaultLocale: true, }, fallback: { zh: 'en', }, }, });

使用方法

1. 在组件中使用翻译

--- import { useI18n } from "../i18n/useI18n"; const { locale, t } = useI18n(Astro); --- <h1>{t("home_title")}</h1> <p>{t("welcome_message")}</p>

2. 生成带语言前缀的URL

--- // 获取带语言前缀的URL const getUrl = (path: string) => { return locale === 'en' ? path : `/${locale}${path}`; }; --- <a href={getUrl("/about")}>{t("about")}</a>

3. 添加新的翻译内容

src/i18n/locales.ts 中的 translations 对象添加新的键值对:

export const translations = { en: { // ... new_key: 'English translation', }, zh: { // ... new_key: '中文翻译', } };

4. 添加新的语言

  1. src/i18n/locales.ts 中添加新语言:

    export const locales = { en: { name: 'English', code: 'en' }, zh: { name: '中文', code: 'zh' }, ja: { name: '日本語', code: 'ja' } // 新增日语 };
  2. 添加新语言的翻译内容:

    export const translations = { en: { /* ... */ }, zh: { /* ... */ }, ja: { home: 'ホーム', computers: 'コンピューター', // ... } };
  3. astro.config.mjs 中添加新语言:

    i18n: { defaultLocale: 'en', locales: ['en', 'zh', 'ja'], // 添加ja // ... }

路由结构

  • 英文默认路由: / (首页), /about (关于), /blog (博客)
  • 中文路由: /zh (首页), /zh/about (关于), /zh/blog (博客)

注意事项

  1. 添加新页面时,确保在所有语言的翻译文件中添加相应的翻译内容
  2. 链接处理:始终使用 getUrl() 函数生成带语言前缀的URL
  3. 图片和静态资源:无需特殊处理,使用相对路径即可
  4. 表单和动态内容:需要手动处理表单标签和提示信息的翻译

扩展建议

  1. 添加更多语言:按照上述步骤添加其他语言支持
  2. 翻译管理工具:考虑使用专业的翻译管理工具(如i18next)来管理大量翻译内容
  3. SEO优化:为不同语言版本的页面添加合适的meta标签和hreflang属性
  4. 内容管理:使用CMS管理多语言内容,实现内容和代码分离