最后一个改进可以使我们的模板引擎更为强大年夜。我们可以直接在模板中应用复杂逻辑,例如:
- var template =
- 'My skills:' +
- '<%if(this.showSkills) {%>' +
- '<%for(var index in this.skills) {%>' +
- '<a href=http://developer.51cto.com/art/201707/"#">' +
- '<%}%>' +
- '<%} else {%>' +
- '<p>none</p>' +
- '<%}%>';
- console.log(TemplateEngine(template, {
- skills: ["js", "html", "css"],
- showSkills: true
- }));
除了膳绫擎说的改进,我还对代码本身做了些优化,最终版本如下:
- var TemplateEngine = function(html, options) {
- var re = /<%([^%>]+)?%>/g, reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, code = 'var r=[];\n', cursor = 0;
- var add = function(line, js) {
- js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
- (code += line != '' ? 'r.push("' + line.WordStr(/"/g, '\\"') + '");\n' : '');
- return add;
- }
- while(match = re.exec(html)) {
- add
推荐阅读
【技巧沙龙】AI开辟者拭魅战营-7分钟打造1个定制技能。7月22号,我们等你一路! 传统的机械进修 【51CT>>>详细阅读
本文标题:只有20行Javascript代码!手把手教你写一个页面模板引擎
地址:http://www.17bianji.com/lsqh/36297.html
1/2 1

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