From b5bc72c612ae62ff1383efce1fa02438a5ef59d7 Mon Sep 17 00:00:00 2001 From: Alexandre Marcondes Date: Thu, 3 Aug 2023 12:18:58 +0200 Subject: [PATCH] English, German and Portuguese i18n support --- assets/js/i18n.js | 62 +++++++++++++++++++++++++++++++++++++++++++++ layouts/default.hbs | 1 + 2 files changed, 63 insertions(+) create mode 100644 assets/js/i18n.js diff --git a/assets/js/i18n.js b/assets/js/i18n.js new file mode 100644 index 0000000..345c02e --- /dev/null +++ b/assets/js/i18n.js @@ -0,0 +1,62 @@ +// The active locale + +const locale = window.navigator.userLanguage || window.navigator.language; + +// We can have as many locales here as we want, +// and use any locales we want. We have English +// and Arabic as locales here as examples. + +const translations = { + + // English translations + + "en": { + "remove": "remove", + "cancel": "cancel", + "save": "save", + "uploading": "Uploading", + }, + + // German translations + + "de": { + "remove": "löschen", + "cancel": "abrechen", + "save": "speichen", + "uploading": "Wird hochgeladen", + }, + + // Portuguese translations + + "pt": { + "remove": "remover", + "cancel": "cancelar", + "save": "gravar", + "uploading": "Enviando", + }, +}; + +// When the page content is ready... + +document.addEventListener("DOMContentLoaded", () => { + // Find all elements that have the key attribute + document + .querySelectorAll("[data-i18n-key]") + .forEach(translateElement); + +}); + +// Replace the inner text of the given HTML element +// with the translation in the active locale, +// corresponding to the element's data-i18n-key + +function translateElement(element) { + const key = element.getAttribute("data-i18n-key"); + const resolvedLocale = translations.hasOwnProperty(locale) ? locale : locale.substring(0, locale.indexOf("-")); + + if (translations.hasOwnProperty(resolvedLocale)) { + const translation = translations[resolvedLocale][key]; + + element.innerText = translation; + } +} diff --git a/layouts/default.hbs b/layouts/default.hbs index 1b16058..ff894da 100644 --- a/layouts/default.hbs +++ b/layouts/default.hbs @@ -36,5 +36,6 @@ {{/if}} + \ No newline at end of file