本项目已配置为支持中英文双语的电商网站。以下是配置的详细说明和使用指南。
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: '电脑',
// ...
}
};
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
};
}
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>
astro.config.mjs - 配置国际化路由和默认语言:
export default defineConfig({
i18n: {
defaultLocale: 'en',
locales: ['en', 'zh'],
routing: {
prefixDefaultLocale: false,
redirectToDefaultLocale: true,
},
fallback: {
zh: 'en',
},
},
});
--- import { useI18n } from "../i18n/useI18n"; const { locale, t } = useI18n(Astro); --- <h1>{t("home_title")}</h1> <p>{t("welcome_message")}</p>
--- // 获取带语言前缀的URL const getUrl = (path: string) => { return locale === 'en' ? path : `/${locale}${path}`; }; --- <a href={getUrl("/about")}>{t("about")}</a>
在 src/i18n/locales.ts 中的 translations 对象添加新的键值对:
export const translations = {
en: {
// ...
new_key: 'English translation',
},
zh: {
// ...
new_key: '中文翻译',
}
};
在 src/i18n/locales.ts 中添加新语言:
export const locales = {
en: { name: 'English', code: 'en' },
zh: { name: '中文', code: 'zh' },
ja: { name: '日本語', code: 'ja' } // 新增日语
};
添加新语言的翻译内容:
export const translations = {
en: { /* ... */ },
zh: { /* ... */ },
ja: {
home: 'ホーム',
computers: 'コンピューター',
// ...
}
};
在 astro.config.mjs 中添加新语言:
i18n: {
defaultLocale: 'en',
locales: ['en', 'zh', 'ja'], // 添加ja
// ...
}
/ (首页), /about (关于), /blog (博客)/zh (首页), /zh/about (关于), /zh/blog (博客)getUrl() 函数生成带语言前缀的URL