//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=[];\n',
cursor = 0;
var add = function (line, js) {
code += js ? line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n'
: 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
}
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\n]/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);