diff --git a/src/components/LanguageSwitcher.astro b/src/components/LanguageSwitcher.astro new file mode 100644 index 0000000..fa1ebec --- /dev/null +++ b/src/components/LanguageSwitcher.astro @@ -0,0 +1,172 @@ +--- +import { getSupportedLangs, getTranslator } from '@/i18n/utils'; +import i18n from '@/i18n'; +import { IoChevronDown } from 'react-icons/io5'; + +const { url } = Astro; +// 使用 fallbackLng 作为回退值 +const currentLocale = + Astro.currentLocale || + (Array.isArray(i18n.options.fallbackLng) + ? i18n.options.fallbackLng[0] + : i18n.options.fallbackLng) || + 'en'; +const t = await getTranslator(currentLocale); + +const supportedLangs = getSupportedLangs(); +const defaultLocaleCode = 'en'; + +let basePath = url.pathname; +const prefix = `/${currentLocale}`; + +// 只有当当前语言不是硬编码的默认语言时,才需要尝试移除前缀 +if (currentLocale !== defaultLocaleCode && basePath.startsWith(prefix)) { + basePath = basePath.substring(prefix.length) || '/'; +} +if (basePath !== '/' && !basePath.startsWith('/')) { + basePath = '/' + basePath; +} + +const currentLangName = + t(`languages.${currentLocale}`) || currentLocale.toUpperCase(); +--- + +