• 模板引擎的简单原理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','代码块');
    
    ​
    

      

  • 相关阅读:
    有种感觉叫失去才知道珍惜
    Alternativa 3D Series – Tutorial 1 – Getting Started
    ruby中使用MiniMagick处理图片
    RMagick动态生成图片
    Rails Model验证之强大
    Rails验证信息的中文化
    Prawn:Ruby生成PDF更简捷的选择
    ruby gem相关命令使用
    Ruby Gems(1)–简要介绍和ruby on rails安装
    Rails安装
  • 原文地址:https://www.cnblogs.com/itlyh/p/6045754.html
Copyright © 2020-2023  润新知