需要在前端把資料套進 HTML 樣板時,很多人會直接引入 Handlebars、Mustache 等套件。但其實一個堪用的模板引擎只需要二十行左右——這正是 John Resig 當年那篇著名文章的洞察。本文重現整個推導過程,每一步都能自己動手驗證。
我們想要的是這樣的介面:
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 }));
// <p>Hello, my name is Krasimir. I'm 29 years old.</p>
var re = /<%([^%>]+)?%>/g; var match = re.exec(tpl); // [ "<%name%>", " name ", index: 21, input: "..." ]
這個正則會擷取所有以 <% 開頭、%> 結尾的片段。末尾的 g(global)表示要找出全部而非只有一個。但 exec 單次只回傳一筆,所以要用 while 迴圈:
var re = /<%([^%>]+)?%>/g;
while (match = re.exec(tpl)) {
console.log(match);
}
// 會依序印出 <%name%> 與 <%age%>
var TemplateEngine = function(tpl, data) {
var re = /<%([^%>]+)?%>/g;
while (match = re.exec(tpl)) {
tpl = tpl.replace(match[0], data[match[1]]);
}
return tpl;
};
這能跑,但只要你傳入巢狀的資料結構就立刻破功:
{ name: "Krasimir Tsonev", profile: { age: 29 } }
模板中寫 <%profile.age%> 時,程式會去查 data['profile.age'],得到 undefined。
與其自己實作點號取值,不如直接讓使用者寫 this.profile.age,然後把整段模板編譯成 JavaScript 函式。這靠的是 new Function:
var fn = new Function("arg", "console.log(arg + 1);");
fn(2); // 3
等價於:
var fn = function(arg) { console.log(arg + 1); };
fn(2);
也就是說,我們可以從字串動態組出函式的參數與函式主體。那麼,如果最終的函式主體長得像這樣,一切就通了:
return "<p>Hello, my name is " + this.name + ". I'm " + this.profile.age + " years old.</p>";
字串相加在遇到流程控制時會立刻爆炸:
return 'My skills:' + for(var index in this.skills) { + '<a>' + this.skills[index] + '</a>' + }
這是語法錯誤。改為把片段推進陣列,最後再 join:
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('');
這樣一般文字、表達式、流程語句就能一律塞進同一個陣列,編譯出來的程式碼永遠合法。
var TemplateEngine = function(tpl, data) {
var re = /<%([^%>]+)?%>/g,
code = 'var r=[];\n',
cursor = 0;
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); // JavaScript 表達式
cursor = match.index + match[0].length;
}
add(tpl.substr(cursor, tpl.length - cursor));
code += 'return r.join("");';
console.log(code);
return tpl;
};
cursor 記住上次解析到哪裡,就能把兩個佔位符之間的文字切出來。注意 add 中必須把雙引號轉義,否則產生的程式碼會語法錯誤。此時印出的 code 是:
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("");
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data);
用 apply(data) 呼叫,就會把 data 設為函式的 this,這正是模板裡能寫 this.name 的原因。參數都不用另外傳。
目前若模板寫了迴圈,for(...) 會被包成 r.push(for(...)) 而報語法錯誤。解法是多一個正則來判斷這行是否為流程語句:
var re = /<%([^%>]+)?%>/g,
reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g;
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;
};
符合關鍵字就直接寫進程式碼,否則包成 push。編譯結果變成:
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("");
於是條件判斷與迴圈都能用了:
var template = 'My skills:' +
'<%if(this.showSkills) {%>' +
'<%for(var index in this.skills) {%>' +
'<a href="#"><%this.skills[index]%></a>' +
'<%}%>' +
'<%} else {%>' +
'<p>none</p>' +
'<%}%>';
TemplateEngine(template, { skills: ["js", "html", "css"], showSkills: true });
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);
};
add 回傳自己,因此可以串接呼叫 add(a)(b, true),這是小技巧,但也讓程式碼更緊湊。
它示範了一個重要的觀念:把「資料替換」問題轉換成「程式碼生成」問題。一旦模板被編譯成真正的 JavaScript,if、for、巢狀取值、甚至自訂函式呼叫全都免費附贈,因為那些本來就是 JavaScript 的能力。你今天用的 Vue、React 的模板編譯,背後都是同一個想法。
理解原理是一回事,實際使用又是另一回事。這個 15 行版本有幾個嚴重問題:
安全性:這是 XSS 的溫床。模板中的 <%this.name%> 會把使用者輸入直接插入 HTML。若 name 是 <img src=x onerror=alert(1)>,就直接執行了。真正的模板引擎都提供「自動轉義」與「明確標示為安全的 HTML」兩種模式,這個版本兩者都沒有。
new Function 無法使用嚴格模式與 CSP。它等同 eval,在設定了 Content-Security-Policy 的網站上會直接被阻擋,也无法做靜態分析與最佳化。
錯誤訊息幾乎無法除錯。語法錯誤發生在動態產生的字串上,行號對不回原始模板,堆疊追蹤也沒有意義。
因此結論很清楚:拿它來理解編譯式模板的原理,但真正開發請用成熟方案——需要簡單字串插值就用 ES6 的模板字面串 `Hello ${name}`;需要 HTML 模板就用 lit-html、Handlebars,或直接上前端框架。特別是 lit-html,它的設計哲學與本文幾乎同源(把模板編譯成可重複執行的函式),但同時解決了安全與效能問題,很值得對照閱讀。