Skip to content

Instantly share code, notes, and snippets.

@NuckChorris
Created September 5, 2011 22:11
Show Gist options
  • Select an option

  • Save NuckChorris/1196042 to your computer and use it in GitHub Desktop.

Select an option

Save NuckChorris/1196042 to your computer and use it in GitHub Desktop.
var regex = /\{([a-zA-Z\.0-9]*)\}/mg;
var getObject = function (obj, str) {
var parts = str.split('.');
for (var i = 0, l = parts.length; i < l; ++i) {
if (!obj[parts[i]] || obj[parts[i]] === null) {
return null;
}
obj = obj[parts[i]];
}
return obj;
};
module.exports = function (template, obj) {
if (arguments.length === 1) {
return template;
} else if (arguments.length === 2) {
if (arguments[1] == null) {
return template;
} else if (typeof arguments[1] === 'object') {
var obj = arguments[1];
} else if (typeof arguments[1] === 'Array') {
var obj = arguments[1];
} else {
var obj = [arguments[1]];
}
} else if (arguments.length > 1) {
var obj = Array.slice.call(arguments, 1);
} else {
return template;
}
return template.replace(regex, function (match, name) {
return getObject(obj, name) || match;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment