Skip to content

Instantly share code, notes, and snippets.

@lamchau
Created July 10, 2015 17:30
Show Gist options
  • Save lamchau/4e6b12be41c7c6d4afbd to your computer and use it in GitHub Desktop.
Save lamchau/4e6b12be41c7c6d4afbd to your computer and use it in GitHub Desktop.
(function(I18n) {
if (!I18n) {
throw new Error('Missing dependency: I18n');
}
var translate = I18n.translate;
var slice = [].slice;
/**
* // en.js
* var translation = {
* add: function(options) {
* if (options) {
* return 'Add: {{type}}';
* }
* return 'Add';
* }
* };
*
* I18n.t('add'); // 'Add'
* I18n.t('add', { type: 'foo'); // 'Add: foo'
* I18n.t('add', { type: 'baz'); // 'Add: baz'
*/
// TODO: add PR to I18n for optional placeholder
I18n.translate = function(scope, options) {
var translation = translate.apply(I18n, arguments);
// optional placeholder
if (typeof(translation) === 'function') {
var args = slice.call(arguments);
args.shift();
var value = translation.apply(null, args);
if (typeof(value) === 'string') {
args.unshift(value);
return I18n.interpolate.apply(I18n, args);
}
var errorMessage = I18n.missingTranslation.apply(I18n, args);
return errorMessage.replace('[missing', '[invalid');
}
return translation;
};
// re-alias
I18n.t = I18n.translate;
})(I18n);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment