Created
December 3, 2014 08:00
-
-
Save keenwon/d9cefdd9576ddc28c031 to your computer and use it in GitHub Desktop.
简单的javascript模板引擎
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 templateEngine(tpl, data) { | |
var reg = /\{\{(?!\}\})(.*?)\}\}/g, | |
regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, | |
code = 'var r=[];\n', | |
cursor = 0, | |
match; | |
var add = function(line, js) { | |
js ? (code += line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n') : | |
(code += line !== '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : ''); | |
return add; | |
}; | |
while (match = reg.exec(tpl)) { | |
add(tpl.slice(cursor, match.index))(match[1], true); | |
cursor = match.index + match[0].length; | |
} | |
add(tpl.substr(cursor, tpl.length - cursor)); | |
code += 'return r.join("");'; | |
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment