49
src/i18n/utils.ts
Normal file
49
src/i18n/utils.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import {
|
||||
DEFAULT_LOCALE,
|
||||
LOCALES,
|
||||
PREFIX_DEFAULT_LOCALE,
|
||||
isLocaleSegment,
|
||||
type Locale,
|
||||
} from './config';
|
||||
import { translate } from './dictionary';
|
||||
|
||||
/**
|
||||
* 从当前 URL 解析语言:
|
||||
* - 路径首段若是支持的语言前缀(如 /cn/shows → cn)则用之;
|
||||
* - 否则回退到默认语言(en)。
|
||||
*/
|
||||
export function getLocaleFromUrl(url: URL | string): Locale {
|
||||
const pathname = typeof url === 'string' ? url : url.pathname;
|
||||
const seg = pathname.split('/').filter(Boolean)[0];
|
||||
return isLocaleSegment(seg) ? seg : DEFAULT_LOCALE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成带语言前缀的链接。
|
||||
* - en(默认且 PREFIX_DEFAULT_LOCALE=false)→ /shows
|
||||
* - cn → /cn/shows
|
||||
* 第二个参数可指定目标语言,方便做语言切换器。
|
||||
*/
|
||||
export function useTranslatedPath(locale: Locale) {
|
||||
return (path: string, targetLocale: Locale = locale): string => {
|
||||
const clean = path.startsWith('/') ? path : `/${path}`;
|
||||
if (targetLocale === DEFAULT_LOCALE && !PREFIX_DEFAULT_LOCALE) return clean;
|
||||
return `/${targetLocale}${clean}`;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 取翻译函数 t():key 即英文原文,按当前语言自动匹配翻译。
|
||||
* - 英文环境:t('All Shows') 直接返回 'All Shows'(key 本身)
|
||||
* - 中文环境:t('All Shows') 返回字典里的 '全部走秀'(取不到则回退英文)
|
||||
* - 支持 {name} 形式的插值参数。
|
||||
*/
|
||||
export function useTranslations(locale: Locale) {
|
||||
function t(key: string, params?: Record<string, string | number>): string {
|
||||
return translate(key, locale, params);
|
||||
}
|
||||
return { t, locale };
|
||||
}
|
||||
|
||||
export { LOCALES, DEFAULT_LOCALE };
|
||||
export type { Locale };
|
||||
Reference in New Issue
Block a user