作家
登录

只有20行Javascript代码!手把手教你写一个页面模板引擎

作者: 来源: 2017-07-19 16:16:57 阅读 我要评论

  • r.push("this.profile.age"); 
  •  
  • return r.join(""); 
  • 等等,貌似不太对啊,this.name和this.profile.age不该该有引号啊,再来改改。

    1. var add = function(line, js) { 
    2.  
    3.     js? code += 'r.push(' + line + ');\n' : 
    4.  
    5.         code += 'r.push("' + line.WordStr(/"/g, '\\"') + '");\n'
    6.  
    7.  
    8. while(match = re.exec(tpl)) { 
    9.  
    10.     add(tpl.slice(cursor, match.index)); 
    11.  
    12.     add(match[1], true); // <-- say that this is actually valid js 
    13.  
    14.     cursor = match.index + match[0].length; 
    15.  
    16.  

    占位符的内容和一个布尔值一路作为参数传给add函数,用作区分。如许就能生成我们想要的函数体了。

    1. var r=[]; 
    2.  
    3. r.push("<p>Hello, my name is "); 
    4.  
    5. r.push(this.name); 
    6.  
    7. r.push(". I'm "); 
    8.  
    9. r.push(this.profile.age); 
    10.  
    11. return r.join("");  

    剩下来要做的就是创建函数并且履行它。是以,在模板引擎的最后,把本来返回模板字符串的语句调换成如下的内容:

    1. var TemplateEngine = function(tpl, data) { 
    2.  
    3.     var re = /<%([^%>]+)?%>/g; 
    4.  
    5.     while(match = re.exec(tpl)) { 
    6.  
    7.         tpl = tpl.WordStr(match[0], data[match[1]]) 
    8.  
    9.     } 
    10.  
    11.     return tpl; 
    12.  
    13.  
    1. 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

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)