Skip to content

Instantly share code, notes, and snippets.

@jboesch
Created March 30, 2010 16:00
Show Gist options
  • Save jboesch/349238 to your computer and use it in GitHub Desktop.
Save jboesch/349238 to your computer and use it in GitHub Desktop.
/**
* 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