溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

JavaScript模板引擎原理與用法詳解

發(fā)布時(shí)間:2020-10-17 10:32:34 來(lái)源:腳本之家 閱讀:134 作者:坦GA 欄目:web開(kāi)發(fā)

本文實(shí)例講述了JavaScript模板引擎原理與用法。分享給大家供大家參考,具體如下:

一、前言

什么是模板引擎,說(shuō)的簡(jiǎn)單點(diǎn),就是一個(gè)字符串中有幾個(gè)變量待定。比如:

var tpl = 'Hei, my name is <%name%>, and I\'m <%age%> years old.';

通過(guò)模板引擎函數(shù)把數(shù)據(jù)塞進(jìn)去,

var data = {
  "name": "Barret Lee",
  "age": "20"
};
var result = tplEngine(tpl, data);
//Hei, my name is Barret Lee, and I'm 20 years old.

那這玩意兒有什么作用呢?其實(shí)他就是一個(gè)預(yù)處理器(preprocessor),搞php開(kāi)發(fā)的童鞋對(duì)Smarty必然是十分熟悉,Smarty是一個(gè)php模板引擎,tpl中待處理的字符通過(guò)數(shù)據(jù)匹配然后輸出相應(yīng)的html代碼,加之比較給力的緩存技術(shù),其速度和易用性是非常給力的!JS Template也是一樣的,我們的數(shù)據(jù)庫(kù)里保存著數(shù)以千萬(wàn)計(jì)的數(shù)據(jù),而每一條數(shù)據(jù)都是通過(guò)同一種方式輸入,就拿上面的例子來(lái)說(shuō),我們不可能在數(shù)據(jù)庫(kù)里存幾千條"Hei, my name...",而是只保存對(duì)應(yīng)的name和age,通過(guò)模板輸出結(jié)果。

JS模板引擎應(yīng)該做哪些事情?看看下面一串代碼:

var tpl = '<% for(var i = 0; i < this.posts.length; i++) {' + 
  'var post = posts[i]; %>' +
  '<% if(!post.expert){ %>' +
    '<span>post is null</span>' +
  '<% } else { %>' +
    '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><% post.expert %> at <% post.time %></a>' +
  '<% } %>' +
'<% } %>';

一個(gè)基本的模板引擎至少可以保證上面的代碼可以正常解析。如送入的數(shù)據(jù)是:

var data = {
  "posts": [{
    "expert": "content 1",
    "time": "yesterday"
  },{
    "expert": "content 2",
    "time": "today"
  },{
    "expert": "content 3",
    "time": "tomorrow"
  },{
    "expert": "",
    "time": "eee"
  }]
};

可以輸出:

<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 1 at yesterday</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 2 at today</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >content 3 at tomorrow</a>
<span>post is null</span>

下面就具體說(shuō)說(shuō)這個(gè)模板引擎的原理是啥樣的。

二、JS模板引擎的實(shí)現(xiàn)原理

1.正則摳出要匹配的內(nèi)容

針對(duì)這一串代碼,通過(guò)正則獲取內(nèi)容

var tpl = 'Hei, my name is <%name%>, and I\'m <%age%> years old.';
var data = {
  "name": "Barret Lee",
  "age": "20"
};

最簡(jiǎn)單的方式就是通過(guò)replace函數(shù)了:

var result = tpl.replace(/<%([^%>]+)?%>/g, function(s0, s1){
  return data[s1];
});

通過(guò)正則替換,我們很輕松的拿到了result,你可以去試一試,他正是我們想要的結(jié)果。但是這里又有了一個(gè)問(wèn)題,改一下data和tpl,

var tpl = 'Hei, my name is <%name%>, and I\'m <%info.age%> years old.';
var data = {
  "name": "Barret Lee",
  "info": { age": "20"}
};

再用上面的方式去獲取結(jié)果,呵呵,不行了吧~ 這里data["info.age"]本身就是undefined,所以我們需要換一種方式來(lái)處理這個(gè)問(wèn)題,那就是將它轉(zhuǎn)換成真正的JS代碼。如:

return 'Hei, my name is ' + data.name + ', and I\'m ' + data.info.age' + ' years old.'

但是接著又有一個(gè)問(wèn)題來(lái)了,當(dāng)我們的代碼中出現(xiàn)for循環(huán)和if的時(shí)候,上面的轉(zhuǎn)換明顯是不起作用的,如:

var tpl = 'Posts: ' +
     '<% for(var i = 0; i < post.length; i++) {'+
      '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><% post[i].expert %></a>' +
     '<% } %>'

如果繼續(xù)采用上面的方式,得到的結(jié)果便是:

return 'Posts: ' +
    for(var i = 0; i < post.length; i++) { +
     '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >' + post[i].exper + '</a>' +
    }

這顯然不是我們?cè)敢饪吹降?,稍微觀察一下上面的結(jié)構(gòu),如果可以返回一個(gè)這樣的結(jié)果也挺不錯(cuò)哦:

'Posts: '
for(var i = 0; i < post.length; i++) {
  '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >' + post[i].exper + '</a>'
}

但是我們需要得到的是一個(gè)字符串,而不是上面這樣零散的片段,因此可以把這些東西裝入數(shù)組中。

2.裝入數(shù)組

var r = [];
r.push('Posts: ' );
r.push(for(var i = 0; i < post.length; i++) {);
r.push('<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >');
r.push(post[i].exper);
r.push('</a>');
r.push(});

有人看到上面的代碼就要笑了,第三行和最后一行代碼的邏輯明顯是不正確的嘛,那腫么辦呢?呵呵,很簡(jiǎn)單,不放進(jìn)去就行了唄,

var r = [];
r.push('Posts: ' );
for(var i = 0; i < post.length; i++) {
  r.push('<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >');
  r.push(post[i].exper);
  r.push('</a>');
}

這樣的邏輯就十分完善了,不存在太多的漏洞,但是這個(gè)轉(zhuǎn)化的過(guò)程是如何實(shí)現(xiàn)的?我們必須還是要寫(xiě)一個(gè)解析的模板函數(shù)出來(lái)。

3.分辨js邏輯部分

var r = [];
tpl.replace(/<%([^%>]+)?%>/g, function(s0, s1){
  //完蛋了,這里貌似又要回到上面那可笑的邏輯有錯(cuò)誤的一步啦... 該怎么處理比較好?
});

完蛋了,這里貌似又要回到上面那可笑的邏輯有錯(cuò)誤的一步啦... 該怎么處理比較好?我們知道,JS給我們提供了構(gòu)造函數(shù)的“類(lèi)”,

var fn = new Function("data",
  "var r = []; for(var i in data){ r.push(data[i]); } return r.join(' ')");
fn({"name": "barretlee", "age": "20"}); // barretlee 20

知道了這個(gè)就好辦了,我們可以把邏輯部分和非邏輯部分的代碼鏈接成一個(gè)字符串,然后利用類(lèi)似fn的函數(shù)直接編譯代碼。而/<%([^%>]+)?%>/g,這一個(gè)正則只能把邏輯部分匹配出來(lái),要想把所有的代碼都組合到一起,必須還得匹配非邏輯部分代碼。replace函數(shù)雖然很強(qiáng)大,他也可以完成這個(gè)任務(wù),但是實(shí)現(xiàn)的邏輯比較晦澀,所以我們換另外一種方式來(lái)處理。

先看一個(gè)簡(jiǎn)單的例子:

var reg = /<%([^%>]+)?%>/g;
var tpl = 'Hei, my name is <%name%>, and I\'m <%age%> years old.';
var match = reg.exec(tpl);
console.log(match);

看到的是:

[
  0: "<%name%>",
  1: name,
  index: 16,
  input: "Hei, my name is <%name%>, and I'm <%age%> years old."
  length: 2
]

這。。。我們可是想得到所有的匹配啊,他竟然只獲取了name而忽略了后面的age,好吧,對(duì)正則稍微熟悉點(diǎn)的童鞋一定會(huì)知道應(yīng)該這樣處理:

var reg = /<%([^%>]+)?%>/g;
while(match = reg.exec(tpl)) {
  console.log(match);
}

關(guān)于正則表達(dá)式的內(nèi)容就不在這里細(xì)說(shuō)了,有興趣的同學(xué)可以多去了解下match,exec,search等正則的相關(guān)函數(shù)。這里主要是靠match的index屬性來(lái)定位遍歷位置,然后利用while循環(huán)獲取所有的內(nèi)容。

4.引擎函數(shù)

所以我們的引擎函數(shù)雛形差不多就出來(lái)了:

var tplEngine = function(tpl, data){
  var reg = /<%([^%>]+)?%>/g,
      code = 'var r=[];\n',
      cursor = 0; //主要的作用是定位代碼最后一截
  var add = function(line) {
    code += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
  };
  while(match = reg.exec(tpl)) {
    add(tpl.slice(cursor, match.index)); //添加非邏輯部分
    add(match[1]); //添加邏輯部分 match[0] = "<%" + match[1] + "%>";
    cursor = match.index + match[0].length;
  }
  add(tpl.substr(cursor, tpl.length - cursor)); //代碼的最后一截 如:" years old."
  code += 'return r.join("");'; // 返回結(jié)果,在這里我們就拿到了裝入數(shù)組后的代碼
  console.log(code);
  return tpl;
};

這樣一來(lái),測(cè)試一個(gè)小demo:

 

var tpl = '<% for(var i = 0; i < this.posts.length; i++) {' + 
    'var post = posts[i]; %>' +
    '<% if(!post.expert){ %>' +
      '<span>post is null</span>' +
    '<% } else { %>' +
      '<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><% post.expert %> at <% post.time %></a>' +
    '<% } %>' +
  '<% } %>';
tplEngine(tpl, data);

返回的結(jié)果讓人很滿(mǎn)意:

var r=[];
r.push("");
r.push(" for(var i = 0; i < this.posts.length; i++) {var post = posts[i]; ");
r.push("");
r.push(" if(!post.expert){ ");
r.push("<span>post is null</span>");
r.push(" } else { ");
r.push("<a href=\"#\">");
r.push(" post.expert ");
r.push(" at ");
r.push(" post.time ");
r.push("</a>");
r.push(" } ");
r.push("");
r.push(" } ");
r.push("");
return r.join("");

不過(guò)我們并需要for,if,switch等這些東西也push到r數(shù)組中去,所以呢,還得改善下上面的代碼,如果在line中發(fā)現(xiàn)了包含js邏輯的代碼,我們就不應(yīng)該讓他進(jìn)門(mén):

regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g;
var add = function(line, js) {
  js? code += line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n' :
    code += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
};

所以我們只剩下最后一步工作了,把data扔進(jìn)去!

5.把data扔進(jìn)去

沒(méi)有比完成這東西更簡(jiǎn)單的事情啦,通過(guò)上面對(duì)Function這個(gè)函數(shù)的講解,大家應(yīng)該也知道怎么做了。

return new Function(code).apply(data);

使用apply的作用就是讓code中的一些變量作用域綁定到data上,不然作用域就會(huì)跑到global上,這樣得到的數(shù)據(jù)索引就會(huì)出問(wèn)題啦~ 當(dāng)然我們可以再優(yōu)化一下:

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

把回車(chē)換行以及tab鍵都給匹配掉,讓代碼更加干凈一點(diǎn)。那么最終的代碼就是:

var tplEngine = function(tpl, data) {
  var reg = /<%([^%>]+)?%>/g,
    regOut = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
    code = 'var r=[];\n',
    cursor = 0;
  var add = function(line, js) {
    js? (code += line.match(regOut) ? line + '\n' : 'r.push(' + line + ');\n') :
      (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
    return add;
  }
  while(match = reg.exec(tpl)) {
    add(tpl.slice(cursor, match.index))(match[1], true);
    cursor = match.index + match[0].length;
  }
  add(tpl.substr(cursor, tpl.length - cursor));
  code += 'return r.join("");';
  return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
};

三、應(yīng)用場(chǎng)景

畢竟是前端代碼,所以寫(xiě)出來(lái)是要為前端服務(wù)的,平時(shí)我們處理的一般是一個(gè)html的模板,通常的情況下,模板代碼是放在script標(biāo)簽或者textarea中,所以首先是要獲取到這里頭的東西,然后再來(lái)做解析。

var barretTpl = function(str, data) {
  //獲取元素
  var element = document.getElementById(str);
  if (element) {
    //textarea或input則取value,其它情況取innerHTML
    var html = /^(textarea|input)$/i.test(element.nodeName) ? element.value : element.innerHTML;
    return tplEngine(html, data);
  } else {
    //是模板字符串,則生成一個(gè)函數(shù)
    //如果直接傳入字符串作為模板,則可能變化過(guò)多,因此不考慮緩存
    return tplEngine(str, data);
  }
  var tplEngine = function(tpl, data) {
    // content above
  };
};

這樣一來(lái)就更加簡(jiǎn)單了,使用方式就是 barretTpl(str, data), 這里的str可以是模板代碼,也可以是一個(gè)DOM元素的id~

四、優(yōu)化以及功能拓展

總共就三四十行代碼,完成的東西肯定是一個(gè)簡(jiǎn)潔版的,不過(guò)對(duì)于一個(gè)簡(jiǎn)單的頁(yè)面而言,這幾行代碼已經(jīng)足夠使用了,如果還想對(duì)他做優(yōu)化,可以從這幾個(gè)方面考慮:

  • 優(yōu)化獲取的模板代碼,比如去掉行尾空格等
  • 符號(hào)轉(zhuǎn)義,如果我們想輸出<span>hehe</span>類(lèi)似這樣的源代碼,在push之前必須進(jìn)行轉(zhuǎn)義
  • 代碼緩存,如果一個(gè)模板會(huì)經(jīng)常使用,可以將它用一個(gè)數(shù)組緩存在barretTpl閉包內(nèi)
  • 用戶(hù)自己設(shè)置分隔符

更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專(zhuān)題:《javascript面向?qū)ο笕腴T(mén)教程》、《JavaScript切換特效與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》

希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI