模板引擎
var syntaxTplEngine = function(tpl, data) {
var re = /<%([^%>]+)%>/g,
code = 'var r=[];\n',
cursor = 0,
reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g;
var addCode = function(line, js) {
js ? code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n' :
code += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
}
while(match = re.exec(tpl)) {
addCode(tpl.slice(cursor, match.index));
addCode(match[1], true);
cursor = match.index + match[0].length;
}
addCode(tpl.substr(cursor, tpl.length - cursor));
code += 'return r.join("");';
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
};
使用方法:syntaxTplEngine(tmpl, data);
心似浮云常自在,意如流水任东西

浙公网安备 33010602011771号