首页 > 代码库 > 模板解析DEMO

模板解析DEMO

let render = function (str, data) {
let tpl = str.replace(/<%=([\s\S]+?)%>/g,function (match, code) {
return "‘ +obj."+code+"+ ‘";
}) ;

tpl = "var tpl=‘"+tpl+"‘\n return tpl;";
let complied = new Function(‘obj‘,tpl);
return complied(data);
};

let tpl = "Hello <%=username%>.";
console.log(render(tpl,{username:"dana"}));

//上面这种做法每次都要编译执行。可以简化,使得编译一次,多次执行。
//具体做法就是生成一个函数,然后返回,吧参数当做参数传递

let compile = function (str) {
let tpl = str.replace(/<%=([\s\S]+?)%>/g,function (match, code) {
return "‘ +obj."+code+"+‘";
});

tpl = "var tpl = ‘"+tpl+"‘\nreturn tpl";
return new Function(‘obj,escape‘,tpl);
};
let render1 = function (compile, data) {
return compile(data);
};

let res = render1(compile,"Hello <%=username%>.");
console.log(res({username:"dana1"}));

模板解析DEMO