Skip to content

Instantly share code, notes, and snippets.

@werelax
Created October 23, 2011 14:49
Show Gist options
  • Save werelax/1307438 to your computer and use it in GitHub Desktop.
Save werelax/1307438 to your computer and use it in GitHub Desktop.
Microscopic JavaScript template system
function LousyTemp(text) {
var code = '%>' + text + '<%';
code = code
.replace(/[\n\r\t]/g," ")
.replace(/(["'])/g, '\\$1')
.replace(/<%=(.*?)%>/g, "', $1, '")
.replace(/%>(.*?)<%/g, "_t_.push('$1'); ");
code = "obj||(obj={}); var _t_ = []; with(obj) {" + code + "}; return _t_.join('');";
return new Function('obj', code);
}
/** Example:
var temp = LousyTemp('<h1 id="<%= id %>"> <% if (cond) { %> TRUE COND <% } else { %> FALSE COND <% } %> </h1>');
console.log(temp({cond: false, id: "Test"});
// -> <h1 id="Test"> FALSE COND </h1>
console.log(temp({cond: true, id: "AnotherTest"});
// -> <h1 id="AnotherTest"> TRUE COND </h1>
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment