前端模板引擎能讓 DOM 的組裝擺脫繁瑣的字串拼接,提升可維護性與效能。本文從模板引擎的作用與原理談起,並一步步實作一個名為 ice 的原生 JavaScript 模板引擎。
原理十分單純:物件(資料)+ 模板(含變數)→ 字串(HTML)。實作上,是透過解析模板,依詞法將其轉為一個函式,呼叫時傳入資料物件,即可輸出 HTML 字串。
var tpl = 'i am <%= name%>, <%= age%> years old'; // <%=xxx%> 詞法,標記為變數
var obj = {
name : 'lovesueee' ,
age : 24
};
var fn = Engine.compile(tpl); // 編譯成函數
var str = fn(obj); // 渲染出字符串模板可直接寫在頁面中的 script 標籤裡,支援迴圈、條件判斷與 include 子模板:
<script type="text/html" id="tpl">
<div>here is the render result:</div>
<% = this.title() ;%>
<table border=1>
<% for(var i=0,tl = this.trs.length,tr;i<tl;i++){ %>
<% tr = this.trs[i]; if (tr.sex === "女") { %>
<tr>
<td><%= tr.name; %></td>
<td><%= tr.age; %></td>
<td><%= tr.sex || "男" %></td>
</tr>
<% } %>
<% } %>
</table>
<img src="<%= this.href %>">
<%= this.include('tpl2',this); %>
</script>渲染時傳入資料與 view helper:
var elem = document.getElementById('tpl');
var tpl = elem.innerHTML;
var html = ice(tpl,{
trs: trs,
href: "https://images.jb51.net/type4.jpg"
},{
title: function(){
return "<p>這是使用視圖helper輸出的代碼片斷</p>";
}
});
$("#content").html(html);核心的解析與編譯邏輯如下:
(function (win) {
// 模板引擎路由函數
var ice = function (id, content) {
return ice[
typeof content === 'object' ? 'render' : 'compile'
].apply(ice, arguments);
};
ice.version = '1.0.0';
// 模板配置
var iConfig = {
openTag : '<%',
closeTag : '%>'
};
var isNewEngine = !!String.prototype.trim;
// 模板緩存
var iCache = ice.cache = {};
// 輔助函數
var iHelper = {
include : function (id, data) {
return iRender(id, data);
},
print : function (str) {
return str;
}
};
// 原型繼承
var iExtend = Object.create || function (object) {
function Fn () {};
Fn.prototype = object;
return new Fn;
};
// 模板編譯
var iCompile = ice.compile = function (id, tpl, options) {
var cache = null;
id && (cache = iCache[id]);
if (cache) {
return cache;
}
if (typeof tpl !== 'string') {
var elem = document.getElementById(id);
if (elem) {
options = tpl;
tpl = elem.value || elem.innerHTML;
} else {
tpl = id;
id = null;
}
}
options = options || {};
var render = iParse(tpl, options);
id && (iCache[id] = render);
return render;
};
// 模板渲染
var iRender = ice.render = function (id, data, options) {
return iCompile(id, options)(data);
};
var iForEach = Array.prototype.forEach ?
function(arr, fn) {
arr.forEach(fn)
} :
function(arr, fn) {
for (var i = 0; i < arr.length; i++) {
fn(arr[i], i, arr)
}
};
// 模板解析
var iParse = function (tpl, options) {
var html = [];
var js = [];
var openTag = options.openTag || iConfig['openTag'];
var closeTag = options.closeTag || iConfig['closeTag'];
// 根據浏覽器采取不同的拼接字符串策略
var replaces = isNewEngine
?["var out='',line=1;", "out+=", ";", "out+=html[", "];", "this.result=out;"]
: ["var out=[],line=1;", "out.push(", ");", "out.push(html[", "]);", "this.result=out.join('');"];
var body = replaces[0];
iForEach(tpl.split(openTag), function(val, i) {
if (!val) { return; }
var parts = val.split(closeTag);
var head = parts[0];
var foot = parts[1];
var len = parts.length;
if (len === 1) {
body += replaces[3] + html.length + replaces[4];
html.push(head);
} else {
if (head ) {
head = head
.replace(/^\s+|\s+$/g, '')
.replace(/[\r\n]+\s*/, '');
if (head.indexOf('=') === 0) {
head = head.substring(1).replace(/^\s+|[s;]+$/g, '');
body += replaces[1] + head + replaces[2];
} else {
body += head;
}
body += 'line+=1;';
js.push(head);
}
if (foot) {
_foot = foot.replace(/^[\r\n]+\s*/g, '');
if (!_foot) { return; }
body += replaces[3] + html.length + replaces[4];
html.push(foot);
}
}
});
body = "var Render=function(data){ice.mix(this, data);try{"
+ body
+ replaces[5]
+ "}catch(e){ice.log('rend error : ', line, 'line');ice.log('invalid statement : ', js[line-1]);throw e;}};"
+ "var proto=Render.prototype=iExtend(iHelper);"
+ "ice.mix(proto, options);"
+ "return function(data){return new Render(data).result;};";
var render = new Function('html', 'js', 'iExtend', 'iHelper', 'options', body);
return render(html, js, iExtend, iHelper, options);
};
ice.log = function () {
if (typeof console === 'undefined') { return; }
var args = Array.prototype.slice.call(arguments);
console.log.apply && console.log.apply(console, args);
};
// 合並對象
ice.mix = function (target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
};
// 注冊函數
ice.on = function (name, fn) {
iHelper[name] = fn;
};
// 清除緩存
ice.clearCache = function () {
iCache = {};
};
// 更改配置
ice.set = function (name, value) {
iConfig[name] = value;
};
// 暴露接口
if (typeof module !== 'undefined' && module.exports) {
module.exports = template;
} else {
win.ice = ice;
}
})(window);這個引擎的巧思在於:以 openTag 與 closeTag 切分模板,將純 HTML 段落推進陣列,並把 <%= %> 內的程式碼拼接進函式主體,最終透過 new Function 動態編譯為可執行函式。同時,它針對有無 String.prototype.trim 的瀏覽器,採用不同的字串拼接策略以優化效能,並內建 include、print 等輔助函式與快取機制。理解這個流程,就能自行打造或改造適合專案需求的模板引擎。