Created
January 11, 2016 19:34
-
-
Save youmad/2bd3d8195f2a28a59c21 to your computer and use it in GitHub Desktop.
Micro template engine in JS.
This file contains hidden or 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
var tplNgn = function(qs, opts) { | |
var html = document.querySelector(qs).innerHTML; | |
var re = /<%([^%>]+)?%>/g; | |
var reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g; | |
var code = 'var r=[];\n'; | |
var cursor = 0; | |
var match; | |
var add = function(line, js) { | |
if (js) { | |
code += (line.match(reExp)) | |
? line + '\n' | |
: 'r.push(' + line + ');\n'; | |
} else { | |
code += (line != '') | |
? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' | |
: ''; | |
}; | |
return add; | |
}; | |
while (match = re.exec(html)) { | |
add(html.slice(cursor, match.index))(match[1], true); | |
cursor = match.index + match[0].length; | |
}; | |
add(html.substr(cursor, html.length - cursor)); | |
code += 'return r.join("");'; | |
return new Function(code.replace(/[\r\t\n]/g, '')).apply(opts); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment