Skip to content

Instantly share code, notes, and snippets.

@jeremyaboyd
Last active October 31, 2017 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyaboyd/3af316e81829ec25fbf59791536e9920 to your computer and use it in GitHub Desktop.
Save jeremyaboyd/3af316e81829ec25fbf59791536e9920 to your computer and use it in GitHub Desktop.
Simple Translation Resource Lookup - Useful in client side applications
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