Using i18n in Javascript :)
by Brynner
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">...</div>
JavaScript
/* _config.js */
appConfig = {
locale: {
code: 'enUS'
}
}
/* _i18n.js */
/**
* Get a nested object property by passing
* a dot notation string as the property name
*/
var getPropertyValue = function(obj, desc) {
var arr = desc.split('.');
while (arr.length && (obj = obj[arr.shift()]));
return obj;
}
/**
* Para uso em trechos de código JavaScript,
* onde os valores dos parâmetros são inseridos no texto
* Exemplo:
* text('account.welcome', {username: 'Brynner'});
*/
var text = function(name, params = {}) {
var i18n = appConfig.locale[appConfig.locale.code](params);
return getPropertyValue(i18n, name);
}
/**
* Automaticamente mapeia os data-atributos 'data-text'
* para adicionar o respectivo texto do idioma
* Exemplo:
* <p data-text="account.welcome" data-text-params='{"username": "Brynner"}'></p>
*/
$(function () {
$('[data-text]').each(function(){
var dataText = $(this).attr('data-text');
var dataTextParams = $(this).attr('data-text-params') ? JSON.parse($(this).attr('data-text-params')) : '';
var textToAdd = text(dataText, dataTextParams);
$(this).html(textToAdd);
});
});
/* 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;