website/assets/js/i18n.js
2024-03-06 15:55:00 +01:00

62 lines
2.1 KiB
JavaScript

function getTranslation(obj, path) {
return path.reduce((xs, x) => (xs && xs[x] !== undefined) ? xs[x] : undefined, obj);
}
function changeLanguage(lang) {
document.cookie = `lang=${lang};path=/;max-age=31536000;SameSite=None${window.location.protocol === 'https:' ? '; Secure' : ''}`;
fetch(`/assets/i18n/${lang}.json`)
.then(response => response.json())
.then(translations => {
document.querySelectorAll('[data-i18n]').forEach(elem => {
const keys = elem.getAttribute('data-i18n').split('.');
const translation = getTranslation(translations, keys);
if (translation !== undefined) {
// If the element is an input, update its value; otherwise, update its innerHTML
if (elem.tagName.toLowerCase() === 'input') {
elem.value = translation;
} else {
elem.innerHTML = translation;
}
}
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(elem => {
const keys = elem.getAttribute('data-i18n-placeholder').split('.');
const translation = getTranslation(translations, keys);
if (translation !== undefined) {
elem.placeholder = translation;
}
});
});
document.getElementById('languageSelect').value = lang;
}
function getCookie(name) {
let cookieArray = document.cookie.split(';');
for(let i = 0; i < cookieArray.length; i++) {
let cookiePair = cookieArray[i].split('=');
if(name == cookiePair[0].trim()) {
return decodeURIComponent(cookiePair[1]);
}
}
return null;
}
function initializeLanguage() {
const availableLanguages = ['en', 'de']; // Extend as necessary
let userLang = getCookie('lang');
if (!userLang) {
let systemLang = navigator.language.split('-')[0];
userLang = availableLanguages.includes(systemLang) ? systemLang : 'en';
}
changeLanguage(userLang);
}
// Run the initialization function when the page loads
initializeLanguage();