Last active
October 31, 2017 17:10
-
-
Save jeremyaboyd/3af316e81829ec25fbf59791536e9920 to your computer and use it in GitHub Desktop.
Simple Translation Resource Lookup - Useful in client side applications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var translation = { | |
phrases: { | |
"vest": { | |
"": "Vest", | |
"en-GB": "Waistcoat", | |
"es": "Chaleco", | |
"fr": "Gilet" | |
}, | |
}, | |
/** | |
* Returns the translation of a given phrase key. | |
* @param {string} key - The key of the translation phrase to look up | |
* @param {string} [language=] - The Language Culture Name of the translation phrase you wish to use; Uses a fall back logic (example: "en-AU" -> "en" -> "") | |
*/ | |
getTranslation: function (key, language) { | |
language = language || navigator.language || ""; | |
languageParts = language.split('-'); | |
if (!translation.phrases[key]) throw `"${key}" not found`; | |
return translation.phrases[key][language] || | |
translation.phrases[key][languageParts[0]] || | |
translation.phrases[key][""]; | |
}, | |
importTranslation: function(language, phrases) { | |
for(let phrase in phrases) { | |
if(!translation.phrases.hasOwnProperty(phrase)) | |
translation.phrases[phrase] = {}; | |
translation.phrases[phrase][language] = phrases[phrase]; | |
} | |
} | |
} | |
// example of importing a language (hr-HR.js) | |
// Croatian - Croatia | |
translation.importTranslation("hr-HR", { | |
"vest": "Prsluk", | |
"another key": "..." | |
}); | |
// test outputs | |
console.log(translation.getTranslation("vest")); //Vest | |
console.log(translation.getTranslation("vest", "en-GB")); //Waistcoat | |
console.log(translation.getTranslation("vest", "hr-HR")); //Prsluk | |
console.log(translation.getTranslation("jacket")); //"jacket" not found |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment