Skip to content

Instantly share code, notes, and snippets.

@filmaj
Created March 7, 2011 23:38
Show Gist options
  • Save filmaj/859523 to your computer and use it in GitHub Desktop.
Save filmaj/859523 to your computer and use it in GitHub Desktop.
A tiny templating technique by extending the String prototype in JavaScript
String.prototype.format = function(){
var args = arguments;
obj = (args.length == 1 && (typeof args[0] == 'object')) ? args[0] : args;
return this.replace(/\{(\w+)\}/g, function(m, i){
return obj[i];
});
}
// Example usage:
// Here is a template string
var templateString = '<div class="item"><h1>{username}</h1><p>{description}</p></div>';
// Here is an example data set, a list of users:
var response = [{username:'fil',description:'awesome'},{username:'steve',description:'not so awesome'}];
// Interpolate into the template string
response.forEach(function(user) {
document.write(templateString.format({
username:user.username,
description:user.description
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment