-
-
Save premasagar/442151 to your computer and use it in GitHub Desktop.
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 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