feat: init i18n features
This commit is contained in:
parent
99a981209c
commit
7af0886d9c
3 changed files with 52 additions and 0 deletions
14
src/components/helper/i18n/LanguagePicker.astro
Normal file
14
src/components/helper/i18n/LanguagePicker.astro
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
---
|
||||||
|
import { languages } from '../../../i18n/ui';
|
||||||
|
import { getLangFromUrl, useTranslatedPath } from '../../../i18n/utils';
|
||||||
|
|
||||||
|
const lang = getLangFromUrl(Astro.url);
|
||||||
|
const translatePath = useTranslatedPath(lang);
|
||||||
|
---
|
||||||
|
<ul>
|
||||||
|
{Object.entries(languages).map(([lang, label]) => (
|
||||||
|
<li>
|
||||||
|
<a href={translatePath('/', lang)}>{label}</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
19
src/i18n/ui.ts
Normal file
19
src/i18n/ui.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
export const languages = {
|
||||||
|
en: 'English',
|
||||||
|
zh_hans: '中文(简体)',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const defaultLang = 'en';
|
||||||
|
export const showDefaultLang = false;
|
||||||
|
|
||||||
|
export const ui = {
|
||||||
|
en: {
|
||||||
|
'nav.home': 'Home',
|
||||||
|
'nav.about': 'About',
|
||||||
|
'nav.twitter': 'Twitter',
|
||||||
|
},
|
||||||
|
zh_hans: {
|
||||||
|
'nav.home': '首页',
|
||||||
|
'nav.about': '关于',
|
||||||
|
},
|
||||||
|
} as const;
|
19
src/i18n/utils.ts
Normal file
19
src/i18n/utils.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import {ui, defaultLang, showDefaultLang} from './ui';
|
||||||
|
|
||||||
|
export function getLangFromUrl(url: URL) {
|
||||||
|
const [, lang] = url.pathname.split('/');
|
||||||
|
if (lang in ui) return lang as keyof typeof ui;
|
||||||
|
return defaultLang;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTranslations(lang: keyof typeof ui) {
|
||||||
|
return function t(key: keyof typeof ui[typeof defaultLang]) {
|
||||||
|
return ui[lang][key] || ui[defaultLang][key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTranslatedPath(lang: keyof typeof ui) {
|
||||||
|
return function translatePath(path: string, l: string = lang) {
|
||||||
|
return !showDefaultLang && l === defaultLang ? path : `/${l}${path}`
|
||||||
|
}
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue