模板引擎的理解

2018-08-14  本文已影响0人  gigi1226
songs === [
   {name: '绅士', url: 'http://music.163.com/xxx', singer: '薛之谦'},
   {name: '刚刚好', url: 'http://music.163.com/yyy', singer: '薛之谦'},
   ...
]

两种方法:1.遍历拼接HTML字符串 2.遍历构造DOM对象
一个简化的模板引擎

字符串格式化
before:
var li = '<li>' + song[i].name + '-' + song[i].singer + '</li>'

after:
var li = stringFormat('<li>{0} - {1}</li>', songs[i].name, songs[i].singer)

function stringFormat(string){ // string是变量不是属性,不能使用this
    //params此时为string从1开始之后的数组
    var params = [].slice.call(arguments,1) // arguments为伪数组,数组的方法不能使用 call将arguments设为this

    var regex = /\{(\d+)\}/g  //匹配{一个或多个数字}
    //将字符串中的{n}替换为params[n]
    string = string.replace(regex,function(){
        //function的arguments[1]为字符串中的{n},arguments[0]为字符串中的{n}
        var index = arguments[1]
        console.log(arguments)
        return params[index]
    })//取代为function的返回值
    return string
}


模板文件 : var template = '<p>Hello, my name is <%name%>. I\'m <%age%> years old.</p>';

数据: var data = {
    name: "Krasimir",
    age: 29
}
/*
regex.exec 正则,遍历,匹配
exec在遍历匹配的所有字符串,遍历完后返回null,然后重新遍历
[^%>]不是%或>任一个字符
()正则里分组的意思,分组就是我要用的意思,用括号里的东西
*/
模板引擎: var formatEngine = function (tpl,data){
    var regex = /<%([^%>]+)?%>/g
    while(match = regex.exec(tpl)){ //这里=是赋值
        tpl = tpl.replace(match[0],data[match[1]])
        console.log(tpl)
    }
    return tpl
}
HTML文件:
var string = formatEngine(template,data)
console.log(string)
var fn = new Function("num","console.log(num + 1)"
fn(1)//2
var fn = new Function("num","console.log(num + '1')"
fn(1)//11

等价于

var fn = function(num){
    console.log(num + 1);//函数体
}
fn(1) //2
return 
"<p>Hello, my name is " + 
this.name + 
". I\'m " + 
this.profile.age + 
" years old.</p>";

把所有字符串放在一个数组里,在程序的最后把他们拼接起来

var arr = []
arr.push("<p>Hello, my name is " )
arr.push(this.name)
Arr.push("i am");
Arr.push(this.proflie.age)
Arr.push("years old</p>")
return arr.join('')
//模板文件
var template = '<p>Hello, my name is <%this.name%>. I\'m <%this.profile.age%> years old.</p>'; 
//数据
var data = { 
               name: "zyn", 
               profile: { age: 29 } 
            }

var re = /<%([^%>]+)?%>/g, 
    code = 'var Arr=[];\n',//code保存函数体
    cursor = 0;//cursor游标告诉我们当前解析到了模板的哪个位置,我们需要它来遍历整个模板字符串

//函数add,负责将解析出来的代码行添加到变量code中去
//特别注意:把code包括的双引号字符进行转义,否则代码出错
/*
var func = new Function('x',"console.log(x+\"1\")")
func(1)
*/
var add = function(line){
    //转义
    code += 'arr.push("' + line.relpace(/"/g,'\\"') + '");\n'
}
while(match = regex.exec(tpl)){   
    add(tpl.slice(cursor,match.index))
    add(match[1])
    cursor = match.index + match[0].length
}

第一次while循环时
match=[ 0:“<%this.name%>", 
1:"this.name", 
index:21, 
input:"<p>Hello, my name is<%this.name%>.I'm<%this.profile.age%>years old.</p>",
length:2 
] 
=>tpl.slice(cursor,match.index) //<p>Hello, my name is
add(tpl.slice(cursor,match.index)) 
code=
"
var Arr=[];
Arr.push("<p>Hello, my name is ");
"
match[1] =>"this.name"
cursor = match.index + match[0].length //就是<%this.name%>最后一位的位置
然后依次类推循环

得到

var Arr[]; 
Arr.push("<p>Hello, my name is "); Arr.push("this.name"); 
Arr.push(". I'm "); 
Arr.push("this.profile.age") 
Arr.push("years old </p>") 
return Arr.join("") <p>Hello, my name is <%this.name%>. I'm <%this.profile.age%> years old.</p> 

this.name和this.profile.age不应该有引号

var add = function(line,js){//改变参数,占位符的内容和布尔值做参数
    //转义
    js?code += 'arr.push(' + line + ');\n':// 改动1
       code += 'arr.push("' + line.relpace(/"/g,'\\"') + '");\n'
}
while(match = regex.exec(tpl)){   
    add(tpl.slice(cursor,match.index))
    add(match[1],true) //改动2
    cursor = match.index + match[0].length
}
 }
改动1:三目运算,如果是js 就执行 code += 'Arr.push(' + line + ');\n' 否则执行 code += 'Arr.push("' + line.replace(/"/g, '\\"') + '");\n';

改动2:add(match[1],true);告诉函数add这次传入的是js.

剩下来是创建函数并执行它

return new Function(code.replace(/[\r\t\n]/g,'')).apply(data);

不需要显式的传参数给函数,使用apply方法来调用它,它会自动设定函数执行的上下文,this.name,这里this指向data对象

var template = 'My skills:' + '<%for(var index in this.skills) {%>' + '<a href=""><%this.skills[index]%></a>' + '<%}%>'; var skills= ["js", "html", "css"] 

如果使用字符串拼接的话,代码就应该是下面的样子:

var temolate='My skills:' + 
for(var index in this.skills) { +
'<a href="">' + 
this.skills[index] +
'</a>' +
}

这里会产生一个异常,Uncaught SyntaxError: Unexpected token for。如果我们调试一下,把code变量打印出来,我们就能发现问题所在。

var Arr=[]; 
Arr.push("My skills:"); 
Arr.push(for(var index in this.skills) {); Arr.push("<a href=\"\">"); 
Arr.push(this.skills[index]); 
Arr.push("</a>"); 
Arr.push(}); 
Arr.push(""); 
return Arr.join("");

带for循环的那一行不能直接放到数组里,而是作为脚本的一部分直接运行,所以把内容添加到code变量之前还要做一个判断

最终代码

var templateEngine = function(html,option){
    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 += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
        return add
    }
    while(match = re.exec(html)){
        add(html.slice(cursor,match.index))
        add(match[1],true)
        cursor = match.index + match[0].length
    }
    add(html.substr(cursor,html.length - cursor)) //substr(start,length)
    code += 'return r.join("")'
    return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
}

github代码地址

上一篇 下一篇

猜你喜欢

热点阅读