JavaScript 页面模板引擎

var TemplateEngine = function(html, options) {
    var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];
', cursor = 0;
    var add = function(line, js) {
        js? (code += line.match(reExp) ? line + '
' : 'r.push(' + line + ');
') :
            (code += line != '' ? 'r.push("' + line.replace(/"/g, '\"') + '");
' : '');
        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(/[
	
]/g, '')).apply(options);
}</%([^%>

 

原文地址:https://www.cnblogs.com/wq-gril/p/4911378.html