17 行代碼實現的簡易 Javascript 字符串模板
來自: https://segmentfault.com/a/1190000004428305
首發于 我的博客 轉載請注明出處
</div>
這是源于兩年前,當我在做人生中第一個真正意義上的網站時遇到的一個問題
該網站采用前后端分離的方式,由后端的 REST 接口返回 JSON 數據,再由前端渲染到頁面上。
同許多初學 Javascript 的菜鳥一樣,起初,我也是采用拼接字符串的形式,將 JSON 數據嵌入 HTML 中。開始時代碼量較少,暫時還可以接受。但當頁面結構復雜起來后,其弱點開始變得無法忍受起來:
-
書寫不連貫。每寫一個變量就要斷一下,插入一個 + 和 " 。十分容易出錯。
-
無法重用。HTML 片段都是離散化的數據,難以對其中重復的部分進行提取。
-
無法很好地利用 <template> 標簽 。這是 HTML5 中新增的一個標簽,標準極力推薦將 HTML 模板放入 <template> 標簽中,使代碼更簡潔。
當時我的心情就是這樣的:
為了解決這個問題,我暫時放下了手上的項目,花了半個小時實現一個極簡易的字符串模板。
需求描述
實現一個 render(template, context) 方法,將 template 中的占位符用 context 填充。要求:
-
不需要有控制流成分(如 循環、條件 等等),只要有變量替換功能即可
-
級聯的變量也可以展開
-
被轉義的的分隔符 { 和 } 不應該被渲染,分隔符與變量之間允許有空白字符
例子:
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 }</pre>
實現
先寫下函數的框架:
function render(template, context) {
}</pre>
顯然,要做的第一件事便是 匹配模板中的占位符 。
匹配占位符
匹配的事,肯定是交給正則表達式來完成。那么,這個正則表達式應該長什么樣呢?
根據 需求 1、2 的描述,我們可以寫出:
var reg = /\{([^\{\}]+)\}/g;
至于需求 3,我第一個想到的概念是 前向匹配 ,可惜 Javascript 并不支持,只好用一個折衷的辦法:
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('\\', ''); // 如果 分隔符被轉義,則不渲染
}
// ...
})
}</pre>
占位符替換
嗯,正則表達式確定了,接下來要做的便是替換工作。
根據 需求2,模板引擎不僅要能渲染一級變量,更要渲染多級變量。這該怎么做呢?
其實很簡單:將 token 按 . 分隔開,逐級查找即可:
var variables = token.replace(/\s/g, '').split('.'); // 切割 token
var currentObject = context;
var i, length, variable;
// 逐級查找 context
for (i = 0, length = variables.length, variable = variables[i]; i < length; ++i)
currentObject = currentObject[variable];
return currentObject;</pre>
不過,有可能 token 指定的變量并不存在,這時上面的代碼便會報錯。為了更好的體驗,代碼最好有一定的容錯能力:
var variables = token.replace(/\s/g, '').split('.'); // 切割 token
var currentObject = context;
var i, length, variable;
for (i = 0, length = variables.length, variable = variables[i]; i < length; ++i) {
currentObject = currentObject[variable];
if (currentObject === undefined || currentObject === null) return ''; // 如果當前索引的對象不存在,則直接返回空字符串。
}
return currentObject;</pre>
把所有的代碼組合在一起,便得到了最終的版本:
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, variable = variables[i]; i < length; ++i) {
currentObject = currentObject[variable];
if (currentObject === undefined || currentObject === null) return '';
}
return currentObject;
})
}</pre>
除去空白行,一共 17 行。
將函數掛到 String 的原型鏈
甚至,我們可以通過修改原型鏈,實現一些很酷的效果:
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. </div>