Skip to content

Instantly share code, notes, and snippets.

@srhyne
Created December 29, 2011 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save srhyne/1535589 to your computer and use it in GitHub Desktop.
Save srhyne/1535589 to your computer and use it in GitHub Desktop.
Super simple JS templates with String.prototype.tmpl using Ruby/coffeeScript syntax
String.prototype.tmpl = function(obj){
var str, keys, _do;
//store string
str = this.toString();
//if no object just return string
if(!obj || typeof obj !== "object"){
return str;
}
//get keys in object
keys = Object.keys(obj);
//loop through keys and replace place holders
_do = function(key){
var rgx = new RegExp("#{"+key+"}", "g");
str = str.replace(rgx, obj[key]);
};
keys.forEach(_do);
return str;
}
//just a simple test
function test(){
var tests, template, report, assert;
tests = [];
resultStr = "string : #{str}\n"+
"object : #{obj}\n"+
"Should be : #{result}\n"+
"Passed : #{passed}\n\n";
report = "";
assert = function(test){
test.result = test.str.tmpl(test.obj);
test.passed = test.result === test.should_be;
test.obj = JSON.stringify(test.obj);
report += resultStr.tmpl(test);
};
tests.push({
str : "Hello, #{value}",
obj : { value : "world" },
should_be : "Hello, world"
});
tests.push({
str : "Welcome #{first_name} #{last_name}!",
obj : { first_name : "Stephen", last_name : "Rhyne" },
should_be : "Welcome Stephen Rhyne"
});
tests.forEach(assert);
console.log(report);
}
//was going to use anon but node.js console didn't like it!
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment