码迷,mamicode.com
首页 > 其他好文 > 详细

模板解析DEMO

时间:2017-05-10 00:23:13      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:log   turn   com   dem   参数传递   ret   compile   hello   cape   

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

标签:log   turn   com   dem   参数传递   ret   compile   hello   cape   

原文地址:http://www.cnblogs.com/lliule/p/6833212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!