只有15行的js页面模板引擎

使用15行构建的js页面模板引擎,虽然功能不全,但胜在实用,如下:

              
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
var TemplateEngine = function(tpl, data) { 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 += 'r.push("' + line.replace(/"/g, '\\"') + '");\n'; return add; } while (match = re.exec(tpl)) { add(tpl.slice(cursor, match.index))(match[1], true); cursor = match.index + match[0].length; } add(tpl.substr(cursor, tpl.length - cursor)); code += 'return r.join("");'; // <-- return the result return new Function(code.replace(/[\r\t\n]/g, '')).apply(data); } // 例子 var template = 'My skills:' + '<%if(this.showSkills) {%>' + '<%for(var index in this.skills) {%>' + '<a href="#"><%this.skills[index]%></a>' + '<%}%>' + '<%} else {%>' + '<p>none</p>' + '<%}%>'; console.log(TemplateEngine(template, { skills: ["js", "html", "css"], showSkills: true }));

有用就点个赞吧 🌹

本文于 2018/3/22 上午 发布在 编程 分类下,当前已被围观 1916 次

相关标签:js

永久地址:https://blog.pandashuai.com/article/6