模板引擎

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);

posted @ 2016-08-30 12:44  南烁  阅读(85)  评论(0)    收藏  举报