Skip to content

Instantly share code, notes, and snippets.

Created June 17, 2010 13:46
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 anonymous/442141 to your computer and use it in GitHub Desktop.
Save anonymous/442141 to your computer and use it in GitHub Desktop.
function compile (template) {
function addText (buffer, text, unescaped) {
unescaped = !!unescaped;
buffer.push("\tprint(");
buffer.push(unescaped ? text : "\"" + text
.split("\r").join("\\r")
.split("\n").join("\\n")
.split("\t").join("\\t")
.split("\"").join("\\\"")
+ "\""
);
buffer.push(");\n");
}
function addCode (buffer, code) {
if (code.indexOf("=") == 0) {
addText(buffer, code.substring(1, code.length), true);
} else {
buffer.push("\t" + code);
}
}
var buffer = [];
var re = /(<%|%>)/g;
var prvPos = 0;
var prvSep = "";
while (re.test(template)) {
var curPos = re.lastIndex;
var curSep = template.substring(curPos - 2, curPos);
if (curSep == "<%") {
addText(buffer, template.substring(prvPos, curPos - 2));
} else { //curSep == "%>"
addCode(buffer, template.substring(prvPos, curPos - 2));
}
prvPos = curPos;
prvSep = curSep;
}
if (prvPos < template.length) {
if (prvSep == "%>" || prvSep == "") {
addText(buffer, template.substring(prvPos, template.length));
} else { //prvSep == "%>"
addCode(buffer, template.substring(prvPos, template.length));
}
}
var src =
" var __output = [];\n" +
" var print = function () {\n" +
" __output.push.apply(__output, arguments);\n"+
" };\n" +
buffer.join('') +
" return(__output.join(''));"
;
var template = null;
try {
template = new Function("data", src);
goodCompile = true;
} catch (ex) {
printError("Failed to compile template: " + ex);
}
return(template);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment