模板引擎定义
var TemplateEngine = function(html, options) {
var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0;
var add = function(line, js) {
js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
(code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
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(/[\r\t\n]/g, '')).apply(options);
}
模板定义
var template =
'<%for(var index in this) {%>' +
'<%this[index].theName2.theId%>,' +
'<%this[index].theName2.theUrl%><br>' +
'<%}%>';
加载数据并渲染
$('[data-json]').each(function(){
var temp = eval("(" + $.ajax({url:$(this).data("json"),async:false}).responseText + ")");
$(this).html(TemplateEngine(template, temp));
});
前端HTML绑定模板
<div data-json="json/listInfo.json"></div>