John Resig(jQuery 作者)在《Secrets of the JavaScript Ninja》中分享了一個極精簡的模板引擎(約 20 行代碼),展示「用字串替換生成函數」的核心思想。雖然現代開發多用 Vue/React/Template Literals,但理解其原理有助於掌握模板引擎本質。
(function() {
const cache = {};
this.tmpl = function tmpl(str, data) {
// 1. 判斷是 ID 選擇器還是模板字串
const fn = !/\W/.test(str)
? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML)
: new Function('obj', `
var p=[], print=function(){p.push.apply(p,arguments);};
with(obj){
p.push('${str
.replace(/[\r\t\n]/g, ' ')
.split('<%').join('\t')
.replace(/((^|%>)[^\t]*)'/g, '$1\r')
.replace(/\t=(.*?)%>/g, "',$1,'")
.split('\t').join("');")
.split('%>').join("p.push('")
.split('\r').join("\\'")
}');
}
return p.join('');
`);
// 2. 柯里化:傳 data 則渲染,否則返回編譯後函數
return data ? fn(data) : fn;
};
})();
<script type="text/html" id="item_tmpl">
<div id="<%=id%>" class="<%= i % 2 === 0 ? 'even' : '' %>">
<img src="<%=profile_image_url%>" />
<p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
</div>
</script>
<script type="text/html" id="user_tmpl">
<% for (var i = 0; i < users.length; i++) { %>
<li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
<% } %>
</script>
<%= ... %>:輸出變數值(HTML 轉義需自行處理)<% ... %>:執行任意 JS 代碼(迴圈、判斷)type="text/html":瀏覽器不執行,搜尋引擎忽略,完美隱藏模板const html = tmpl('item_tmpl', {id: 1, from_user: 'John', text: 'Hello'});
document.getElementById('results').innerHTML = html;
const renderItem = tmpl('item_tmpl'); // 返回編譯函數
let html = '';
for (const user of users) {
html += renderItem(user);
}
document.getElementById('results').innerHTML = html;
核心技巧:將模板字串轉換為 JavaScript 字串拼接代碼,再用 `new Function` 動態編譯。
轉換流程示例:
// 原始模板
'<%=name%>'
// 經過 replace/split/join 步驟
// 1. split('<%') -> ['', '=name%>']
// 2. join('\t') -> '\t=name%>'
// 3. replace(/\t=(.*?)%>/g, "',$1,'") -> '\t',name,''
// 4. split('\t').join("');") -> '');',name,''
// 5. split('%>').join("p.push('") -> '');',name,'p.push(''
// 6. 最終包裹在 with(obj){ p.push(' ... '); } return p.join(''); 中
split('match').join('replace') 在舊瀏覽器比 replace(/match/g, 'replace') 更快(現代引擎已優化正則全域替換)。