Last active
September 5, 2018 15:40
-
-
Save brynner/2814611fd6e0312397563db2e937ad10 to your computer and use it in GitHub Desktop.
Using i18n in JavaScript
This file contains hidden or 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
<div id="result">...</div> |
This file contains hidden or 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
/* _i18n.js */ | |
appConfig = { | |
locale: { | |
code: 'enUS' // must reflect the property name of each locale file | |
} | |
} | |
var getPropertyValue = function(obj, desc) { | |
var arr = desc.split('.'); | |
while (arr.length && (obj = obj[arr.shift()])); | |
return obj; | |
} | |
var text = function(name, params = {}) { | |
var i18n = appConfig.locale[appConfig.locale.code](params); | |
return getPropertyValue(i18n, name); | |
} | |
/* pt-br.js */ | |
appConfig.locale.ptBR = function(params) { | |
return { | |
"about": "Sobre", | |
"account": { | |
"welcome": "Boas vindas "+params.username, | |
"info": "Algo aqui." | |
} | |
}; | |
} | |
/* en-us.js */ | |
appConfig.locale.enUS = function(params) { | |
return { | |
"about": "About", | |
"account": { | |
"welcome": "Welcome "+params.username, | |
"info": "Something here." | |
} | |
}; | |
} | |
/* index.js */ | |
var result = text('account.welcome', {username: 'Brynner'}); | |
document.querySelector('#result').innerHTML = result; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://jsfiddle.net/brynner/uhv0Lmyk/