Created
March 10, 2018 22:38
-
-
Save gerardojbaez/90c0a724b98bde82b099a81116427c41 to your computer and use it in GitHub Desktop.
JavaScript Translation Helper Methods
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
/** | |
* Translation helper methods. | |
* | |
* Requries lodash. | |
* | |
* @author Gerardo J. Báez <g@gerardobaez.com> | |
* @license MIT | |
*/ | |
/** | |
* Get translation from i18n array. | |
* | |
* @param {String} key The translation key. | |
* @param {Object} replace The string replacements. | |
* @return {String} | |
*/ | |
window.trans = (key, replace = {}) => { | |
let str = _.get(window.i18n.lines, key) | |
if (! str) { | |
return '' | |
} | |
for (var placeholder in replace) { | |
str = str.replace(new RegExp(`:${placeholder}`, 'g'), replace[placeholder]) | |
} | |
return str | |
} | |
/** | |
* Get translation singular/plural base on count. | |
* | |
* @param {String} key The translation key. | |
* @param {Number} count The count. | |
* @param {Object} replace The string replacements. | |
* @return {String} | |
*/ | |
window.trans_choice = (key, count = 1, replace = {}) => { | |
let str = trans(key, _.merge(replace, { count })) | |
if (! str) { | |
return '' | |
} | |
return _.get(str.split('|'), count > 1 ? 1 : 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment