前端模板引擎核心原理:**模板字串 + 數據對象 → 編譯為渲染函數 → 執行輸出 HTML**。本文解析一個極簡模板引擎 ice 的實現,支援變量輸出、邏輯控制、子模板包含、Helper 函數。
// 編譯模板(id 或字串)
var fn = ice.compile('tplId'); // 或 ice.compile('<%= name %>')
// 渲染
var html = fn({ name: 'Ice' }); // 返回 HTML 字串
// 一步到位
var html = ice('tplId', { name: 'Ice' });
<%= expr %> — 輸出變量/表達式(HTML 轉義)。<% code %> — 執行 JS 邏輯(if/for/函數調用)。<% include('tplId', data) %> — 包含子模板。<% print(str) %> — Helper 輸出原始 HTML。<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; 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>
var ice = function(id, content) {
return ice[typeof content === 'object' ? 'render' : 'compile'].apply(ice, arguments);
};
ice.compile = function(id, tpl) {
// 1. 獲取模板字串(id 或直接字串)
// 2. 正則分割:將 <% ... %> 視為代碼,其餘為字串字面量
// 3. 拼接生成函數體:
// var out = ''; out += '靜態文本'; out += 變量; ... return out;
// 4. new Function('data', 'helpers', funcBody) 創建渲染函數
// 5. 緩存並返回
};
ice.render = function(id, data, helpers) {
var fn = ice.compile(id);
return fn(data, helpers);
};
/<%([\s\S]+?)%>/g 分割代碼塊與文本塊。with(data) { ... } 簡化變量訪問(注意嚴格模式禁用)。{ include: ..., print: ... },模板內用 this.include 調用。ice.cache[id] 避免重複編譯。生產環境建議使用成熟庫:art-template、doT、EJS、Handlebars,支援預編譯、沙箱、SourceMap 等進階特性。