简易模板引擎

2018-03-14  本文已影响0人  你给的恶作剧

简单的需求:

    var template = '<p>Hello, my name is <%name%>. I\'m <%age%> years old.</p>'
          var data = {
              name:'kangkang',
              age:18
          }
    //这里需要直接输出:Hello, my name is kangkang. I\'m 18 years old.

首先我们写一个正则去捕获<%name%>和<%age%>
var re=/<%([^%>]+)?%/g
使用exec()方法去搜索匹配,使用replace去替换

var templateEngine = function(tpl,data){
            var re = /<%([^%>]+)?%>/g
            //exec() 方法在一个指定字符串中执行一个搜索匹配
            while(match = re.exec(tpl)){  //判断match是否为true
                console.log(match)
                //eplace() 方法返回一个由替换值替换一些或所有匹配的模式后的新字符串
                //["<%name%>", "name", index: 21, input: "<p>Hello, my name is <%name%>. I'm <%age%> years old.</p>"]
                tpl = tpl.replace(match[0],data[match[1]])
                //tpl = tpl.replace("<%name%>",data["name"])
                
            }
            return tpl
        }

更复杂的需求:

  var template = 
        'My skillss:' + 
        '<%if(this.showSkills) {%>' +
        '<%for(var index in this.skills) {%>' + 
        '<a href="#"><%this.skills[index]%></a>' +
        '<%}%>' +
        '<%} else {%>' +
        '<p>none</p>' +
        '<%}%>'
  function templateEngine(html,options){}  
  var string = templateEngine(template, {
         skills: ["js", "html", "css"],
         showSkills: true
      })

整体的思路:
1.在template中:
   <% %> 外面,是字符串
   <% %> 里面,是控制语句和变量
2.所以我们可以遍历整个字符串,进行判断
  xxxx 不是以 <% 开头 ==> 'line+= xxxx'
  xxxx 是以<%开头
    是以if/for开头 ==> 'xxx'
    <%for(var index in this.skills) ==>for(var index in this.skills)
    不是以if/for开头 ==> 'line+= xxxx'
    <%this.skills[index]%> ==> this.skills[index]

----------------结果---------------------
var lines = ''
    lines += 'My skills:' 
    if(this.showSkills) {
           for(var index in this.skills) {
                   lines+= '<a href="#">'
                   lines+= this.skills[index]
                   lines+= '</a>' 
             }else
                   lines+= '<p>none</p>'
              }

最终的代码如下

var templateEngine = function(html, options) {
            var re = /<%([^%>]+)?%>/g
            var reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g
            var code = 'var r=[];\n'
            var cursor = 0
            var add = function(line, js) {
                
                js? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :(code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '')

                return add
            }
            while(match = re.exec(html)) {
                // match = <%for(var index in this.skills) {%>,for(var index in this.skills) {
                add(html.slice(cursor, match.index))
                //add('My skillss:')
                add(match[1], true)
                cursor = match.index + match[0].length                
            }
            add(html.substr(cursor, html.length - cursor))
            //substr() 方法返回一个字符串中从指定位置开始到指定字符数的字符。
            code += 'return r.join("");'
            return new Function(code.replace(/[\r\t\n]/g, '')).apply(options)
        }
上一篇 下一篇

猜你喜欢

热点阅读