Skip to content

Instantly share code, notes, and snippets.

@dux
Last active August 29, 2015 14:24
Show Gist options
  • Save dux/33d78f96ef29ef381a51 to your computer and use it in GitHub Desktop.
Save dux/33d78f96ef29ef381a51 to your computer and use it in GitHub Desktop.
Super simple JavaScript prototype templateing
// simple templateing
String.prototype.template = function() {
var formatted = this, arg;
var args = typeof(arguments[0]) === 'object' ? arguments[0] : arguments;
for(arg in args) {
formatted = formatted.replace("{" + arg + "}", args[arg]);
}
return formatted;
};
// send array or object
// <a href="/profile">Dux</a>
'<a href="{1}">{0}</a>'.template('Dux', '/profile');
// <a href="/profile">Dux</a>
'<a href="{url}">{name}</a>'.template({name:'Dux', url:'/profile'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment