Skip to content

Instantly share code, notes, and snippets.

@brynner
Last active September 5, 2018 15:40
Show Gist options
  • Save brynner/2814611fd6e0312397563db2e937ad10 to your computer and use it in GitHub Desktop.
Save brynner/2814611fd6e0312397563db2e937ad10 to your computer and use it in GitHub Desktop.
Using i18n in JavaScript
<div id="result">...</div>
/* _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;
@brynner
Copy link
Author

brynner commented Sep 5, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment