只有20行Javascript代碼!手把手教你寫一個頁面模板引擎
AbsurdJS 作者寫的一篇教程,一步步教你怎樣用 Javascript 實現(xiàn)一個純客戶端的模板引擎。整個引擎實現(xiàn)只有不到 20 行代碼。如果你能從頭看到尾的話,還能有不少收獲的。你甚至可以跟隨大牛的腳步也自己動手寫一個引擎。以下是全文。
不知道你有木有聽說過一個基于Javascript的Web頁面預處理器,叫做AbsurdJS。我是它的作者,目前我還在不斷地完善它。最初我只是打算寫一個CSS的預處理器,不過后來擴展到了CSS和HTML,可以用來把Javascript代碼轉成CSS和HTML代碼。當然,由于可以生成HTML代碼,你也可以把它當成一個模板引擎,用于在標記語言中填充數(shù)據。
于是我又想著能不能寫一些簡單的代碼來完善這個模板引擎,又能與其它現(xiàn)有的邏輯協(xié)同工作。AbsurdJS本身主要是以NodeJS的模塊的形式發(fā)布的,不過它也會發(fā)布客戶端版本??紤]到這些,我就不能直接使用現(xiàn)有的引擎了,因為它們大部分都是在NodeJS上運行的,而不能跑在瀏覽器上。我需要的是一個小巧的,純粹以Javascript編寫的東西,能夠直接運行在瀏覽器上。當我某天偶然發(fā)現(xiàn)John Resig的這篇博客,我驚喜地發(fā)現(xiàn),這不正是我苦苦尋找的東西嘛!我稍稍做了一些修改,代碼行數(shù)差不多20行左右。其中的邏輯非常有意思。在這篇文章中我會一步一步重現(xiàn)編寫這個引擎的過程,如果你能一路看下去的話,你就會明白John的這個想法是多么犀利!
最初我的想法是這樣子的:
- var TemplateEngine = function(tpl, data) {
- // magic here ...
- }
- var template = '<p>Hello, my name is <%name%>. I\'m <%age%> years old.</p>';
- console.log(TemplateEngine(template, {
- name: "Krasimir",
- age: 29
- }));
一個簡單的函數(shù),輸入是我們的模板以及數(shù)據對象,輸出么估計你也很容易想到,像下面這樣子:
- <p>Hello, my name is Krasimir. I'm 29 years old.</p>
其中***步要做的是尋找里面的模板參數(shù),然后替換成傳給引擎的具體數(shù)據。我決定使用正則表達式來完成這一步。不過我不是最擅長這個,所以寫的不好的話歡迎隨時來噴。
- var re = /<%([^%>]+)?%>/g;
這句正則表達式會捕獲所有以<%開頭,以%>結尾的片段。末尾的參數(shù)g(global)表示不只匹配一個,而是匹配所有符合的片段。Javascript里面有很多種使用正則表達式的方法,我們需要的是根據正則表達式輸出一個數(shù)組,包含所有的字符串,這正是exec所做的。
- var re = /<%([^%>]+)?%>/g;
- var match = re.exec(tpl);
如果我們用console.log把變量match打印出來,我們會看見:
- [
- "<%name%>",
- " name ",
- index: 21,
- input:
- "<p>Hello, my name is <%name%>. I\'m <%age%> years old.</p>"
- ]
不過我們可以看見,返回的數(shù)組僅僅包含***個匹配項。我們需要用while循環(huán)把上述邏輯包起來,這樣才能得到所有的匹配項。
- var re = /<%([^%>]+)?%>/g;
- while(match = re.exec(tpl)) {
- console.log(match);
- }
如果把上面的代碼跑一遍,你就會看見<%name%> 和 <%age%>都被打印出來了。
下面,有意思的部分來了。識別出模板中的匹配項后,我們要把他們替換成傳遞給函數(shù)的實際數(shù)據。最簡單的辦法就是使用replace函數(shù)。我們可以像這樣來寫:
- var TemplateEngine = function(tpl, data) {
- var re = /<%([^%>]+)?%>/g;
- while(match = re.exec(tpl)) {
- tpl = tpl.replace(match[0], data[match[1]])
- }
- return tpl;
- }
好了,這樣就能跑了,但是還不夠好。這里我們以data["property"]的方式使用了一個簡單對象來傳遞數(shù)據,但是實際情況下我們很可能需要更復雜的嵌套對象。所以我們稍微修改了一下data對象:
- {
- name: "Krasimir Tsonev",
- profile: { age: 29 }
- }
不過直接這樣子寫的話還不能跑,因為在模板中使用<%profile.age%>的話,代碼會被替換成data[‘profile.age’],結果是undefined。這樣我們就不能簡單地用replace函數(shù),而是要用別的方法。如果能夠在<%和%>之間直接使用Javascript代碼就***了,這樣就能對傳入的數(shù)據直接求值,像下面這樣:
- var template = '<p>Hello, my name is <%this.name%>. I\'m <%this.profile.age%> years old.</p>';
你可能會好奇,這是怎么實現(xiàn)的?這里John使用了new Function的語法,根據字符串創(chuàng)建一個函數(shù)。我們不妨來看個例子:
- var fn = new Function("arg", "console.log(arg + 1);");
- fn(2); // outputs 3
fn可是一個貨真價實的函數(shù)。它接受一個參數(shù),函數(shù)體是console.log(arg + 1);。上述代碼等價于下面的代碼:
- var fn = function(arg) {
- console.log(arg + 1);
- }
- fn(2); // outputs 3
通過這種方法,我們可以根據字符串構造函數(shù),包括它的參數(shù)和函數(shù)體。這不正是我們想要的嘛!不過先別急,在構造函數(shù)之前,我們先來看看函數(shù)體是什么樣子的。按照之前的想法,這個模板引擎最終返回的應該是一個編譯好的模板。還是用之前的模板字符串作為例子,那么返回的內容應該類似于:
- return
- "<p>Hello, my name is " +
- this.name +
- ". I\'m " +
- this.profile.age +
- " years old.</p>";
當然啦,實際的模板引擎中,我們會把模板切分為小段的文本和有意義的Javascript代碼。前面你可能看見我使用簡單的字符串拼接來達到想要的效果,不過這并不是100%符合我們要求的做法。由于使用者很可能會傳遞更加復雜的Javascript代碼,所以我們這兒需要再來一個循環(huán),如下:
- var template =
- 'My skills:' +
- '<%for(var index in this.skills) {%>' +
- '<a href=""><%this.skills[index]%></a>' +
- '<%}%>';
如果使用字符串拼接的話,代碼就應該是下面的樣子:
- return
- 'My skills:' +
- for(var index in this.skills) { +
- '<a href="">' +
- this.skills[index] +
- '</a>' +
- }
當然,這個代碼不能直接跑,跑了會出錯。于是我用了John的文章里寫的邏輯,把所有的字符串放在一個數(shù)組里,在程序的***把它們拼接起來。
- var r = [];
- r.push('My skills:');
- for(var index in this.skills) {
- r.push('<a href="">');
- r.push(this.skills[index]);
- r.push('</a>');
- }
- return r.join('');
下一步就是收集模板里面不同的代碼行,用于生成函數(shù)。通過前面介紹的方法,我們可以知道模板中有哪些占位符(譯者注:或者說正則表達式的匹配項)以及它們的位置。所以,依靠一個輔助變量(cursor,游標),我們就能得到想要的結果。
- var TemplateEngine = function(tpl, data) {
- var re = /<%([^%>]+)?%>/g,
- code = 'var r=[];\n',
- cursor = 0;
- var add = function(line) {
- code += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
- }
- while(match = re.exec(tpl)) {
- add(tpl.slice(cursor, match.index));
- add(match[1]);
- cursor = match.index + match[0].length;
- }
- add(tpl.substr(cursor, tpl.length - cursor));
- code += 'return r.join("");'; // <-- return the result
- console.log(code);
- return tpl;
- }
- var template = '<p>Hello, my name is <%this.name%>. I\'m <%this.profile.age%> years old.</p>';
- console.log(TemplateEngine(template, {
- name: "Krasimir Tsonev",
- profile: { age: 29 }
- }));
上述代碼中的變量code保存了函數(shù)體。開頭的部分定義了一個數(shù)組。游標cursor告訴我們當前解析到了模板中的哪個位置。我們需要依靠它來遍歷整個模板字符串。此外還有個函數(shù)add,它負責把解析出來的代碼行添加到變量code中去。有一個地方需要特別注意,那就是需要把code包含的雙引號字符進行轉義(escape)。否則生成的函數(shù)代碼會出錯。如果我們運行上面的代碼,我們會在控制臺里面看見如下的內容:
- var r=[];
- r.push("<p>Hello, my name is ");
- r.push("this.name");
- r.push(". I'm ");
- r.push("this.profile.age");
- return r.join("");
等等,貌似不太對啊,this.name和this.profile.age不應該有引號啊,再來改改。
- var add = function(line, js) {
- js? code += 'r.push(' + line + ');\n' :
- code += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
- }
- while(match = re.exec(tpl)) {
- add(tpl.slice(cursor, match.index));
- add(match[1], true); // <-- say that this is actually valid js
- cursor = match.index + match[0].length;
- }
占位符的內容和一個布爾值一起作為參數(shù)傳給add函數(shù),用作區(qū)分。這樣就能生成我們想要的函數(shù)體了。
- var r=[];
- r.push("<p>Hello, my name is ");
- r.push(this.name);
- r.push(". I'm ");
- r.push(this.profile.age);
- return r.join("");
剩下來要做的就是創(chuàng)建函數(shù)并且執(zhí)行它。因此,在模板引擎的***,把原本返回模板字符串的語句替換成如下的內容:
- return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
我們甚至不需要顯式地傳參數(shù)給這個函數(shù)。我們使用apply方法來調用它。它會自動設定函數(shù)執(zhí)行的上下文。這就是為什么我們能在函數(shù)里面使用this.name。這里this指向data對象。
模板引擎接近完成了,不過還有一點,我們需要支持更多復雜的語句,比如條件判斷和循環(huán)。我們接著上面的例子繼續(xù)寫。
- var template =
- 'My skills:' +
- '<%for(var index in this.skills) {%>' +
- '<a href="#"><%this.skills[index]%></a>' +
- '<%}%>';
- console.log(TemplateEngine(template, {
- skills: ["js", "html", "css"]
- }));
這里會產生一個異常,Uncaught SyntaxError: Unexpected token for。如果我們調試一下,把code變量打印出來,我們就能發(fā)現(xiàn)問題所在。
- var r=[];
- r.push("My skills:");
- r.push(for(var index in this.skills) {);
- r.push("<a href=\"\">");
- r.push(this.skills[index]);
- r.push("</a>");
- r.push(});
- r.push("");
- return r.join("");
帶有for循環(huán)的那一行不應該被直接放到數(shù)組里面,而是應該作為腳本的一部分直接運行。所以我們在把內容添加到code變量之前還要多做一個判斷。
- 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 += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
- }
這里我們新增加了一個正則表達式。它會判斷代碼中是否包含if、for、else等等關鍵字。如果有的話就直接添加到腳本代碼中去,否則就添加到數(shù)組中去。運行結果如下:
- var r=[];
- r.push("My skills:");
- for(var index in this.skills) {
- r.push("<a href=\"#\">");
- r.push(this.skills[index]);
- r.push("</a>");
- }
- r.push("");
- return r.join("");
當然,編譯出來的結果也是對的。
- My skills:<a href="#">js</a><a href="#">html</a><a href="#">css</a>
***一個改進可以使我們的模板引擎更為強大。我們可以直接在模板中使用復雜邏輯,例如:
- var template =
- 'My skills:' +
- '<%if(this.showSkills) {%>' +
- '<%for(var index in this.skills) {%>' +
- '<a href="#"><%this.skills[index]%></a>' +
- '<%}%>' +
- '<%} else {%>' +
- '<p>none</p>' +
- '<%}%>';
- console.log(TemplateEngine(template, {
- skills: ["js", "html", "css"],
- showSkills: true
- }));
除了上面說的改進,我還對代碼本身做了些優(yōu)化,最終版本如下:
- var TemplateEngine = function(html, options) {
- 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))(match[1], true);
- cursor = match.index + match[0].length;
- }
- add(html.substr(cursor, html.length - cursor));
- code += 'return r.join("");';
- return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
- }
代碼比我預想的還要少,只有區(qū)區(qū)15行!