Created
March 7, 2011 23:38
-
-
Save filmaj/859523 to your computer and use it in GitHub Desktop.
A tiny templating technique by extending the String prototype in JavaScript
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
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