website/assets/js/i18n.js

58 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-03-06 14:19:33 +00:00
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) {
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();