Created
March 30, 2010 16:00
-
-
Save jboesch/349238 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Allow for some super easy templating | |
* @param {Object} ctx The context when you pass in an object literal | |
* ------------------------------------------------------------------ | |
* Works like this: | |
* var People = { name: 'bob', age: 123 } | |
* var my_tpl = "Hi, my name is {{ name }} and I'm {{ age }} years old." | |
* my_tpl.template(People); // Outputs: "Hi, my name is bob and I'm 123 years old"; | |
*/ | |
String.prototype.template = function(data){ | |
return this.replace(/\{\{(.*?)\}\}/g, function (matched, group) { | |
var g = group.replace(/^\s+|\s+$/g, ""); | |
// Only disallow undefined values | |
return (data && typeof(data[g]) !== 'undefined') ? data[g] : matched; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment