這個需求源自我做人生第一個真正意義上的網站時遇到的問題。項目採用前後端分離,後端 REST 接口返回 JSON,前端負責渲染。和很多初學者一樣,我最初用字符串拼接把數據塞進 HTML。代碼量少時還能忍,頁面結構一複雜,短板立刻暴露:
+ 和引號,極易出錯。<template> 標籤:HTML5 推薦把模板放進 template 中,讓結構更清晰,拼接方式天然與之無緣。實現一個 render(template, context) 方法,用 context 填充 template 中的占位符。要求:
{ 和 } 不應被渲染,分隔符與變量之間允許有空白字符。
render('My name is {name}', { name: 'hsfzxjy' });
// My name is hsfzxjy
render('I am in {profile.location}', { name: 'hsfzxjy', profile: { location: 'Guangzhou' } });
// I am in Guangzhou
render('{ greeting }. \\{ This block will not be rendered }', { greeting: 'Hi' });
// Hi. { This block will not be rendered }
匹配交給正則表達式。根據需求一、二,先寫出最直觀的版本:
var reg = /\{([^\{\}]+)\}/g;
至於需求三,我最初想到前向匹配,可惜 JS 不支持,於是採用折衷方案——用分組捕獲轉義反斜線:
var reg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
// 若第一或第三個分組不為空,則說明被轉義,不渲染
function render(template, context) {
var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
return template.replace(tokenReg, function (word, slash1, token, slash2) {
if (slash1 || slash2) {
return word.replace('\\', ''); // 分隔符被轉義,去掉反斜線後原樣輸出
}
// ... 替換邏輯
});
}
模板引擎不仅要能渲染一級變量,還要能渲染多級變量。做法很簡單:把 token 按 . 切開,逐級查找。
var variables = token.replace(/\s/g, '').split('.'); // 去掉空白並切割
var currentObject = context;
var i, length, variable;
for (i = 0, length = variables.length; i < length; ++i) {
currentObject = currentObject[variable];
}
return currentObject;
但如果 token 指向的變量不存在,上面的代碼會報錯。為了更好的容錯體驗,可以在查找過程中判斷並提前返回空字符串:
var variables = token.replace(/\s/g, '').split('.');
var currentObject = context;
var i, length, variable;
for (i = 0, length = variables.length; i < length; ++i) {
currentObject = currentObject[variable];
if (currentObject === undefined || currentObject === null) return '';
}
return currentObject;
function render(template, context) {
var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
return template.replace(tokenReg, function (word, slash1, token, slash2) {
if (slash1 || slash2) {
return word.replace('\\', '');
}
var variables = token.replace(/\s/g, '').split('.');
var currentObject = context;
var i, length, variable;
for (i = 0, length = variables.length; i < length; ++i) {
currentObject = currentObject[variable];
if (currentObject === undefined || currentObject === null) return '';
}
return currentObject;
});
}
除去空白行,一共 17 行。
通過修改原型鏈,還能實現更順手的調用方式:
String.prototype.render = function (context) {
return render(this, context);
};
之後就可以這樣寫:
"{greeting}! My name is { author.name }.".render({ greeting: "Hi", author: { name: "hsfzxjy" } });
// Hi! My name is hsfzxjy.
當然,擴展原生原型存在污染風險,在多人協作或依賴較多的項目中,更建議把 render 作為獨立工具函數引入。而在支持 ES6 的環境裡,直接用模板字符串 `${ author.name }` 往往就能覆蓋大部分場景。