前端模板
var data = { school: '启蒙艾思', cls: { cname: 'qimengs.com' }, arr: ['tool', 'h5', 'mapp'] } var template = `<div><%if(school){%><p><%=school%> </p><%}%><%for (var i = 0; i < arr.length; i++) {%><span><%=arr[i]%></span><%}%> </div> <div> <%=school%> : <%=cls.cname%> </div>`; function tpl(str, data) { var fbody = `var p = []; with(data){${pHTML(str)}};return p.join('')`; return new Function('data', fbody)(data); } function pHTML(str) { str = 'p.push("' + str + '")'; return str.replace(/[\r\n\t]*/g, '') .replace(/<%=(.*?)%>/g, '<%p.push($1);%>') .replace(/<%/g, '");') .replace(/%>/g, 'p.push("') } console.log(tpl(template, data));