萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

輕量級 JavaScript 模板引擎 ice 實現原理與用法

前端模板引擎核心原理:**模板字串 + 數據對象 → 編譯為渲染函數 → 執行輸出 HTML**。本文解析一個極簡模板引擎 ice 的實現,支援變量輸出、邏輯控制、子模板包含、Helper 函數。

核心 API

// 編譯模板(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);
};

關鍵設計點

  1. 詞法分析:用正則 /<%([\s\S]+?)%>/g 分割代碼塊與文本塊。
  2. With 語法:with(data) { ... } 簡化變量訪問(注意嚴格模式禁用)。
  3. Helper 注入:第二參數傳入 { include: ..., print: ... },模板內用 this.include 調用。
  4. 緩存機制:ice.cache[id] 避免重複編譯。

現代替代

生產環境建議使用成熟庫:art-template、doT、EJS、Handlebars,支援預編譯、沙箱、SourceMap 等進階特性。

copyright © 萬盛學電腦網 all rights reserved