javascript template engine

1822 단어 JavaScript
    //var data = {name: "iflytek", year: 1999};

    /**********************************************/
    var getTpl = function(tpl,data){
        var re = /<%([^%>]+)?%>/g;
        while (match = re.exec(tpl)) {
            tpl = tpl.replace(match[0], data[match[1]]);
        }
        return tpl;
    }
    /**********************************************/

    var TemplateEngine = function (tpl, data) {
        var reg = /<%([^%>]+)?%>/g,
            reExp = /(^( )?(if|for|else|{|}))(.*)?/g,
            code = 'var r=[];
', cursor = 0; var add = function (line, js) { code += js ? line.match(reExp) ? line + '
' : 'r.push(' + line + ');
' : 'r.push("' + line.replace(/"/g, '\\"') + '");
'; } while (match = reg.exec(tpl)) { add(tpl.slice(cursor, match.index)); add(match[1], true); cursor = match.index + match[0].length; } add(tpl.slice(cursor, tpl.length)); code += 'return r.join("");'; return new Function(code.replace(/[\r\t
]/g, '')).apply(data); } //var loopTpl = 'name:<%this.info.name%>,site:<%this.info.site%>,building:<%for(var index in this.building){%><h5><%this.building[index]%> </h5><%}%>'; //var data = {info:{name:'iflytek',site:'http://www.iflytek.com'},building:['A1','A2']}; //var str = TemplateEngine(loopTpl,data);

좋은 웹페이지 즐겨찾기