-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.js
57 lines (50 loc) · 1.96 KB
/
translator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Function to dynamically load an external script
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
async function loadLanguage(lang) {
localStorage.setItem('lang', lang);
try {
if (typeof jsyaml === "undefined") {
await loadScript("https://cdn.jsdelivr.net/npm/[email protected]/dist/js-yaml.min.js");
}
const response = await fetch(`/translations/homepage/${lang}.yaml`);
const yamlText = await response.text();
const translations = jsyaml.load(yamlText);
applyTranslations(translations);
} catch (error) {
console.error("Error loading translations:", error);
}
}
function applyTranslations(translations) {
document.querySelectorAll("[data-translate]").forEach(el => {
const key = el.getAttribute("data-translate");
const keys = key.split(".");
let translation = translations;
keys.forEach(k => translation = translation[k] || el.innerHTML);
if (el.hasAttribute("placeholder")) {
el.setAttribute("placeholder", translation);
} else {
el.innerHTML = translation; // Allow HTML formatting like <a> tags
}
});
}
document.addEventListener("DOMContentLoaded", () => {
const lang = localStorage.getItem("lang") || "en";
loadLanguage(lang);
document.getElementById("currentLang").innerText = lang.toUpperCase();
document.querySelectorAll(".lang-select").forEach(item => {
item.addEventListener("click", (event) => {
event.preventDefault();
const selectedLang = event.target.getAttribute("data-lang");
loadLanguage(selectedLang);
document.getElementById("currentLang").innerText = selectedLang.toUpperCase();
});
});
});