Created
October 23, 2011 14:49
-
-
Save werelax/1307438 to your computer and use it in GitHub Desktop.
Microscopic JavaScript template system
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
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