var re = /<%([^%>]+)?%>/g, code = 'var r=[];\n', cursor = 0; var add = function(line) { code += 'r.push("' + line.WordStr(/"/g, '\\"') + '");\n'; } while(match = re.exec(tpl)) { add(tpl.slice(cursor, match.index)); add(match[1]); cursor = match.index + match[0].length; } add(tpl.substr(cursor, tpl.length - cursor)); code += 'return r.join("");'; // < console.log(code); return tpl; } var template = '<p>Hello, my name is <%this.name%>. I\'m <%this.profile.age%> years old.</p>'; console.log(TemplateEngine(template, { name: "Krasimir Tsonev", profile: { age: 29 } })); 上述代码中的变量code保存了函数体。开首的部分定义了一个数组。游标cursor告诉我们当前解析到了模板中的哪个地位。我们须要依附它来遍历全部模板字符串。此外还有个函数add,它负责把解析出来的代码行添加到变量code中去。有一个处所须要特别留意,那就是须要把code包含的双引号字符进行转义(escape)。不然生成的函数代码会掉足。如不雅我们运行膳绫擎的代码,我们会在控制台琅绫擎看见如下的内容:
- var r=[];
-
- r.push("<p>Hello, my name is ");
-
- r.push("this.name");
-
- r.push(". I'm ");
-
推荐阅读
人工智能与机器学习有哪些不同
【技巧沙龙】AI开辟者拭魅战营-7分钟打造1个定制技能。7月22号,我们等你一路!
传统的机械进修
【51CT>>>详细阅读
本文标题:只有20行Javascript代码!手把手教你写一个页面模板引擎
地址:http://www.17bianji.com/lsqh/36297.html
1/2 1