add i18n step1
This commit is contained in:
parent
34d553a890
commit
79e3db6078
23 changed files with 2309 additions and 450 deletions
|
|
@ -10,7 +10,7 @@ const supportedLangs = ['en', 'zh-CN']; // 应用支持的语言列表
|
|||
*/
|
||||
async function loadLocale(lang) {
|
||||
try {
|
||||
const response = await fetch(`/locales/${lang}.json?v=${Date.now()}`);
|
||||
const response = await fetch(`/locales/${lang}.json`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Language file for ${lang} not found (status: ${response.status}).`);
|
||||
}
|
||||
|
|
@ -49,7 +49,14 @@ function applyTranslationsToDOM() {
|
|||
document.querySelectorAll('[data-i18n-title]').forEach(el => {
|
||||
const key = el.dataset.i18nTitle;
|
||||
const translation = t(key);
|
||||
if(translation !== key) el.title = translation;
|
||||
if (translation !== key) el.title = translation;
|
||||
});
|
||||
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
|
||||
const key = el.dataset.i18nPlaceholder;
|
||||
const translation = t(key);
|
||||
if (translation !== key && el.placeholder !== undefined) { // 确保元素有placeholder属性
|
||||
el.placeholder = translation;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -62,7 +69,7 @@ function applyTranslationsToDOM() {
|
|||
export function t(key, replacements = {}) {
|
||||
// 通过路径 'a.b.c' 在嵌套对象中查找值: currentLocale['a']['b']['c']
|
||||
const translation = key.split('.').reduce((obj, k) => obj && obj[k], currentLocale);
|
||||
|
||||
|
||||
let result = translation || key; // 如果找不到, 返回原始key作为回退
|
||||
|
||||
// 处理占位符替换, e.g., {filename: 'example.com'}
|
||||
|
|
@ -71,7 +78,7 @@ export function t(key, replacements = {}) {
|
|||
result = result.replace(`{${placeholder}}`, replacements[placeholder]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
@ -106,4 +113,8 @@ export async function setLanguage(lang) {
|
|||
localStorage.setItem('appLanguage', lang);
|
||||
window.location.reload(); // 刷新页面以应用所有翻译是最简单可靠的方式
|
||||
}
|
||||
}
|
||||
|
||||
export function getCurrentLanguage() {
|
||||
return currentLang;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue