zoukankan      html  css  js  c++  java
  • 模板引擎的简单原理template

    ​
     var templateStr = "我的名字叫<%=name%>我是一只小狗,今年<%=age%>岁。";
            var data = {
                name:'旺财',
                age:'18'
            };
            /*会利用正则来匹配*/
            //console.log(/<%=s*([^%>]+S)s*%>/.exec(templateStr));
            var match = /<%=s*([^%>]+S)s*%>/.exec(templateStr);
            console.log(match);//['<%=name%>',name,....]
            //match[1]--->name   match[0]----><%=name%>
            //data[match[1]]-->'旺财'
            //即将<%=name%> 用 '旺财' 进行替换
            templateStr = templateStr.replace(match[0],data[match[1]]);
            console.log(templateStr);
            match = /<%=s*([^%>]+S)s*%>/.exec(templateStr);
            console.log(match);
            templateStr = templateStr.replace(match[0],data[match[1]]);
            console.log(templateStr);
    
     /*while循环实现将字符串中的所有内容替换掉掉*/
            //匹配到<%=XX%>
            var match = /<%=s*([^%>]+S)s*%>/.exec(templateStr);
            while(match){//match有值
                templateStr = templateStr.replace(match[0],data[match[1]]);//替换
                match = /<%=s*([^%>]+S)s*%>/.exec(templateStr);//继续匹配<%=XX%>
            }
            console.log(templateStr);
    
    //原理!! 
    /*apply 改变函数的上下文当中的this的指向*/
        template.apply({name:'xgg'},['xgg','10']);
        /*也是一个方法也是一个函数*/
        var template = new Function('templateStr','data',
       'var match = /<%=s*([^%>]+S)s*%>/.exec(templateStr);while(match)
       {templateStr = templateStr.replace(match[0],data[match[1]]);
       match = /<%=s*([^%>]+S)s*%>/.exec(templateStr)}console.log(templateStr);');
        template(templateStr,data);
        var template = new Function('name','age','代码块');
    
    ​
    

      

  • 相关阅读:
    es6模块与 commonJS规范的区别 Linda
    hive 子查询特别分析
    C语言I博客作业05
    C语言I博客作业08
    2019秋作业第一周作业
    C语言I博客作业04
    C语言I博客作业09
    C语言I博客作业03
    C语言I博客作业07
    C语言I博客作业06
  • 原文地址:https://www.cnblogs.com/itlyh/p/6045754.html
Copyright © 2011-2022 走看看