From c3c3df473e0e5114b75dbe835ada59a0e8066543 Mon Sep 17 00:00:00 2001 From: Ian Coleman Date: Tue, 29 Nov 2016 16:07:23 +1100 Subject: Translation library does basic language switching --- src/js/translate.js | 140 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 src/js/translate.js (limited to 'src/js/translate.js') diff --git a/src/js/translate.js b/src/js/translate.js new file mode 100644 index 0000000..89512df --- /dev/null +++ b/src/js/translate.js @@ -0,0 +1,140 @@ +// An extremely basic translation library +// +// Example usage: +// +// Set some html to be translated. Do this using the 'data-translate' attribute: +// +//
Test
+//
keep em tag
+// +// +// Obtain all the phrases to be translated via js debug console: +// +// Translate.phrasesAsJson(); +// +// Use that template to translate the phrases into another language. +// Leave the key the same. Change the value to the new language. +// +// Create a js file to load the new phrases. In this example for Spanish, +// es.js will contain the following code: +// +// Translate.loadForeignPhrases("es", { +// "Test": "Test in Spanish", +// "keep em tag": "keep em tag in Spanish", +// "Example text": "Example text in Spanish" +// }); +// +// In your UI put a listener for clicking on the Spanish button: +// +// mySpanishButton.addEventListener("click", function() { +// Translate.setLanguage("es"); +// }); +// myEnglishButton.addEventListener("click", function() { +// Translate.setLanguage("en"); +// }); + +Translate = new (function() { + + var defaultLanguage = "en"; + + var allPhrases = {}; + allPhrases[defaultLanguage] = {}; + + // Node types + + var text = { + selector: "[data-translate]", + getKey: function() { + return this.textContent.trim().replace(/\s+/g, " "); + }, + setPhrase: function(p) { + this.textContent = p; + }, + } + + var html = { + selector: "[data-translate-html]", + getKey: function() { + return this.innerHTML.trim().replace(/\s+/g, " "); + }, + setPhrase: function(p) { + this.innerHTML = p; + }, + } + + var placeholder = { + selector: "[data-translate-placeholder]", + getKey: function() { + return this.getAttribute("placeholder").trim().replace(/\s+/g, " "); + }, + setPhrase: function(p) { + this.setAttribute("placeholder", p); + }, + } + + // Get elements to be translated + var allEls = getEls(text) + .concat(getEls(html)) + .concat(getEls(placeholder)); + + // Provides access to phrases from a non-default language. + // See phrases_en.js for example usage. + this.loadForeignPhrases = function(language, phrases) { + allPhrases[language] = phrases; + } + + // Displays a different language, eg "en" or "fr" + this.setLanguage = function(language) { + for (var i=0; i