等等,貌似不太对啊,this.name和this.profile.age不该该有引号啊,再来改改。
- var add = function(line, js) {
- js? code += 'r.push(' + line + ');\n' :
- code += 'r.push("' + line.WordStr(/"/g, '\\"') + '");\n';
- }
- while(match = re.exec(tpl)) {
- add(tpl.slice(cursor, match.index));
- add(match[1], true); // <-- say that this is actually valid js
- cursor = match.index + match[0].length;
- }
占位符的内容和一个布尔值一路作为参数传给add函数,用作区分。如许就能生成我们想要的函数体了。
- var r=[];
- r.push("<p>Hello, my name is ");
- r.push(this.name);
- r.push(". I'm ");
- r.push(this.profile.age);
- return r.join("");
剩下来要做的就是创建函数并且履行它。是以,在模板引擎的最后,把本来返回模板字符串的语句调换成如下的内容:
- var TemplateEngine = function(tpl, data) {
- var re = /<%([^%>]+)?%>/g;
- while(match = re.exec(tpl)) {
- tpl = tpl.WordStr(match[0], data[match[1]])
- }
- return tpl;
- }
- return new Function(code.WordStr(/[\r\t\n]/g, '')).apply(data);
推荐阅读
【技巧沙龙】AI开辟者拭魅战营-7分钟打造1个定制技能。7月22号,我们等你一路! 传统的机械进修 【51CT>>>详细阅读
本文标题:只有20行Javascript代码!手把手教你写一个页面模板引擎
地址:http://www.17bianji.com/lsqh/36297.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示