萬盛學電腦網

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

JavaScript 模板引擎 Handlebars.js 入門:語義化模板快速構建指南

Handlebars 核心優勢

  • 語義化模板:{{variable}} 語法直觀,邏輯與視圖分離。
  • 零依賴:純 JS,瀏覽器與 Node.js 通用。
  • 預編譯:生產環境可預編譯為 JS 函式,執行極快。
  • Helper 擴展:自訂輔助函式 (如 {{#if}}、{{#each}}、格式化日期)。

快速上手範例

<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Handlebars Demo</title>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/handlebars@4.7.7/dist/handlebars.min.js"></script>
</head><body>

<!-- 1. 模板定義 (隱藏在 script 標籤) -->
<script id="entry-template" type="text/x-handlebars-template">
  <div class="entry">
    <h1>{{title}}</h1>
    <div class="body">{{body}}</div>
  </div>
</script>

<!-- 2. 掛載容器 -->
<div id="content"></div>

<script>
// 3. 取得模板源碼
var source = $("#entry-template").html();

// 4. 編譯為可重用函式
var template = Handlebars.compile(source);

// 5. 準備資料
var data = {
  title: "My New Post",
  body: "This is my first post!"
};

// 6. 渲染並插入 DOM
var html = template(data);
$("#content").html(html);
console.log(html); // 查看生成的 HTML 字串
</script>
</body></html>

核心 API 流程

  1. Handlebars.compile(templateString) → 回傳渲染函式 function(context)。
  2. template(data) → 回傳渲染後 HTML 字串。
  3. 將字串插入 DOM:$(container).html(html) 或 container.innerHTML = html。

常用內建 Helper

Helper用法說明
{{#each array}}{{#each items}} {{this.name}} {{/each}}遍歷陣列/物件,this 指向當前項
{{#if condition}}{{#if user}} 歡迎 {{/if}}條件渲染,falsy 值不渲染
{{#unless condition}}{{#unless isEmpty}} 有內容 {{/unless}}if 反向
{{#with object}}{{#with user}} {{name}} {{/with}}切換上下文
{{lookup}}{{lookup arr 0}}動態鍵值查找

自訂 Helper 範例

Handlebars.registerHelper('formatDate', function(dateStr) {
  var d = new Date(dateStr);
  return d.getFullYear() + '-' + (d.getMonth()+1).toString().padStart(2,'0') + '-' + d.getDate().toString().padStart(2,'0');
});

// 模板使用
// 發布時間:{{formatDate publishTime}}

進階:預編譯部署

# 安裝 CLI
npm install -g handlebars

# 預編譯單一模板
handlebars template.hbs -f template.js

# 預編譯整個目錄
handlebars views/ -f templates.js

# 生產環境僅引入 runtime (體積更小)
<script src="handlebars.runtime.min.js"></script>
<script src="templates.js"></script>
<script> var html = Handlebars.templates['template'](data); </script>

Handlebars 以「Logic-less」哲學(模板內盡量無邏輯)聞名,配合 Helper 機制兼顧表達力。掌握「編譯 → 渲染 → 插入」三步驟,即可在專案中快速導入,替換字串拼接、提升可維護性。

copyright © 萬盛學電腦網 all rights reserved