Last active
January 2, 2019 08:43
-
-
Save fwon/43e33c0166b3de841b5619e3cf7df47c to your computer and use it in GitHub Desktop.
简易前端模板引擎
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
//简易模板引擎实现 | |
//http://krasimirtsonev.com/blog/article/Javascript-template-engine-in-just-20-line | |
//https://segmentfault.com/a/1190000005705169 | |
var TemplateEngine = function(html, options) { | |
var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0, match; | |
var add = function(line, js) { | |
js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') : | |
(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(options); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment