Hugo 模板開發技能
目的
此技能強制執行正確的 Hugo 模板開發實務,包括強制性的執行時期測試,以捕捉靜態建置無法發現的錯誤。
關鍵測試需求
Hugo 的 npx hugo --quiet 僅能驗證模板語法,無法驗證執行時期行為。
存取未定義的欄位、nil 值或不正確的型別斷言等模板錯誤,只會在 Hugo 實際渲染頁面時出現。你必須透過執行伺服器來測試模板。
強制測試協定
進行任何 Hugo 模板變更後
修改 layouts/、layouts/partials/ 或 layouts/shortcodes/ 目錄中的檔案後:
第一步:啟動 Hugo 伺服器並擷取輸出
npx hugo server --port 1315 2>&1 | head -50
成功條件:
- 沒有
error calling partial訊息 - 沒有
can't evaluate field錯誤 - 沒有
template: ... failed訊息 - 伺服器顯示「Web Server is available at http://localhost:1315/」
如果出現錯誤: 修正模板後重複第一步,完成後再繼續。
第二步:確認頁面能正常渲染
curl -s -o /dev/null -w "%{http_code}" http://localhost:1315/PATH/TO/PAGE/
預期結果: HTTP 200 狀態碼
第三步:瀏覽器測試(如果 MCP 瀏覽器工具可用)
如果 mcp__claude-in-chrome__* 工具可用,請使用它們進行視覺檢查:
# 導航並截圖
mcp__claude-in-chrome__navigate({ url: "http://localhost:1315/PATH/", tabId: ... })
mcp__claude-in-chrome__computer({ action: "screenshot", tabId: ... })
# 檢查 JavaScript 錯誤
mcp__claude-in-chrome__read_console_messages({ tabId: ..., onlyErrors: true })
這可以捕捉模板變更可能引入的執行時期 JavaScript 錯誤。
第四步:停止測試伺服器
pkill -f "hugo server --port 1315"
快速測試指令
使用這行單行指令進行測試並立即獲得回饋:
timeout 15 npx hugo server --port 1315 2>&1 | grep -E "(error|Error|ERROR|fail|FAIL)" | head -20; pkill -f "hugo server --port 1315" 2>/dev/null
如果輸出為空,表示未偵測到錯誤。
常見的 Hugo 模板錯誤
1. 存取含連字號的鍵值
錯誤寫法:
{{ .Site.Data.article-data.influxdb }}
正確寫法:
{{ index .Site.Data "article-data" "influxdb" }}
2. 存取 nil 欄位
錯誤寫法:
{{ range $articles }}
{{ .path }} {{/* 如果項目為 nil 或型別錯誤就會失敗 */}}
{{ end }}
正確寫法:
{{ range $articles }}
{{ if . }}
{{ with index . "path" }}
{{ . }}
{{ end }}
{{ end }}
{{ end }}
3. 對 interface{} 進行型別斷言
錯誤寫法:
{{ range $data }}
{{ .fields.menuName }}
{{ end }}
正確寫法:
{{ range $data }}
{{ if isset . "fields" }}
{{ $fields := index . "fields" }}
{{ if isset $fields "menuName" }}
{{ index $fields "menuName" }}
{{ end }}
{{ end }}
{{ end }}
4. 空映射與 nil 的檢查差異
問題: Hugo 的 {{ if . }} 對空映射 {} 會判斷為真:
{{/* 這無法捕獲空映射 */}}
{{ if $data }}
{{ .field }} {{/* 如果 $data 是 {} 仍然會失敗 */}}
{{ end }}
解決方案: 檢查特定鍵值是否存在:
{{ if and $data (isset $data "field") }}
{{ index $data "field" }}
{{ end }}
Hugo 資料存取模式
安全的巢狀存取
{{/* 在每一層都進行 nil 檢查 */}}
{{ $articleDataRoot := index .Site.Data "article-data" }}
{{ if $articleDataRoot }}
{{ $influxdbData := index $articleDataRoot "influxdb" }}
{{ if $influxdbData }}
{{ $productData := index $influxdbData $dataKey }}
{{ if $productData }}
{{ with $productData.articles }}
{{/* 這裡可以安全地使用 . */}}
{{ end }}
{{ end }}
{{ end }}
{{ end }}
安全地迭代資料
{{ range $idx, $item := $articles }}
{{/* 為變數賦予預設值 */}}
{{ $path := "" }}
{{ $name := "" }}
{{/* 安全地提取值 */}}
{{ if isset $item "path" }}
{{ $path = index $item "path" }}
{{ end }}
{{ if $path }}
{{/* 現在可以安全地使用 $path */}}
{{ end }}
{{ end }}
檔案組織
Layouts 目錄結構
layouts/
├── _default/ # 預設模板
├── partials/ # 可複用的模板片段
│ └── api/ # API 專用的 partials
├── shortcodes/ # 內容短碼
└── TYPE/ # 類型專用模板 (api/ 等)
└── single.html # 單頁模板
Partial 命名規則
- 使用描述性名稱:
api/sidebar-nav.html,而非nav.html - 將相關的 partials 歸類到子目錄中
- 在檔案頂端加入註解,說明用途與所需的上下文
關注點分離:模板 vs TypeScript
原則: Hugo 模板負責結構與資料綁定;TypeScript 負責行為與互動性。
職責歸屬
| 關注點 | 位置 | 範例 |
|---|---|---|
| HTML 結構 | layouts/**/*.html | 導覽列標記、分頁容器 |
| 資料綁定 | layouts/**/*.html | {{ .Title }}、{{ range .Data }} |
| 靜態樣式 | assets/styles/**/*.scss | 佈局、色彩、字型 |
| 使用者互動 | assets/js/components/*.ts | 點擊處理器、捲動行為 |
| 狀態管理 | assets/js/components/*.ts | 活躍分頁、已折疊區塊 |
| DOM 操作 | assets/js/components/*.ts | 顯示/隱藏、切換 class |
反模式:模板中的內嵌 JavaScript
錯誤寫法 - JavaScript 與模板混合:
{{/* 不要這樣做 */}}
<nav class="api-nav">
{{ range $articles }}
<button onclick="toggleSection('{{ .id }}')">{{ .name }}</button>
{{ end }}
</nav>
<script>
function toggleSection(id) {
document.getElementById(id).classList.toggle('is-open');
}
</script>
正確寫法 - 清晰的關注點分離:
模板(layouts/partials/api/sidebar-nav.html):
<nav class="api-nav" data-component="api-nav">
{{ range $articles }}
<button class="api-nav-group-header" aria-expanded="false">
{{ .name }}
</button>
<ul class="api-nav-group-items">
{{/* 項目 */}}
</ul>
{{ end }}
</nav>
TypeScript(assets/js/components/api-nav.ts):
interface ApiNavOptions {
component: HTMLElement;
}
export default function initApiNav({ component }: ApiNavOptions): void {
const headers = component.querySelectorAll('.api-nav-group-header');
headers.forEach((header) => {
header.addEventListener('click', () => {
const isOpen = header.classList.toggle('is-open');
header.setAttribute('aria-expanded', String(isOpen));
header.nextElementSibling?.classList.toggle('is-open', isOpen);
});
});
}
在 main.js 中註冊:
import initApiNav from './components/api-nav.js';
const componentRegistry = {
'api-nav': initApiNav,
// ... 其他元件
};
資料傳遞模式
透過 data-* 屬性將 Hugo 資料傳遞給 TypeScript:
模板:
<div
data-component="api-toc"
data-headings="{{ .headings | jsonify | safeHTMLAttr }}"
data-scroll-offset="80"
>
</div>
TypeScript:
interface TocOptions {
component: HTMLElement;
}
interface TocData {
headings: string[];
scrollOffset: number;
}
function parseData(component: HTMLElement): TocData {
const headingsRaw = component.dataset.headings;
const headings = headingsRaw ? JSON.parse(headingsRaw) : [];
const scrollOffset = parseInt(component.dataset.scrollOffset || '0', 10);
return { headings, scrollOffset };
}
export default function initApiToc({ component }: TocOptions): void {
const data = parseData(component);
// 使用 data.headings 與 data.scrollOffset
}
最少量的內嵌腳本(例外情況)
唯一可接受的內嵌腳本是那些必須在元件註冊之前執行的最小初始化程式碼:
{{/* 可接受:關鍵路徑,不含任何邏輯,立即執行 */}}
<script>
document.documentElement.dataset.theme =
localStorage.getItem('theme') || 'light';
</script>
所有其他程式碼都應放在 assets/js/ 目錄下。
元件的檔案組織
assets/
├── js/
│ ├── main.js # 進入點、元件註冊表
│ ├── components/
│ │ └── api-toc.ts # API 目錄的行為
│ └── utils/
│ └── dom-helpers.ts # 共用的 DOM 工具函式
└── styles/
└── layouts/
├── _api-layout.scss # API 頁面佈局(三欄、側邊欄、目錄)
└── _api-operations.scss # 操作渲染(方法、參數、回應)
TypeScript 元件檢查清單
建立新的互動功能時:
- 在
assets/js/components/中建立 TypeScript 檔案 - 為元件選項定義介面
- 匯出預設的初始器函式
- 在
main.js的componentRegistry中註冊 - 在 HTML 元素上加入
data-component屬性 - 透過
data-*屬性傳遞資料(而非使用內嵌 JavaScript) - 模板中不得包含
<script>標籤
偵錯模板
啟用詳細模式
npx hugo server --port 1315 --verbose 2>&1 | head -100
列印變數以進行偵錯
{{/* 暫時性的偵錯用 - 提交前請移除 */}}
<pre>{{ printf "%#v" $myVariable }}</pre>
檢查資料檔案載入情況
# 確認資料檔案存在且是有效的 YAML
cat data/article-data/influxdb/influxdb3-core/articles.yml | head -20
與 CI/CD 整合
推薦的 Pre-commit Hook
加入 .lefthook.yml 或 pre-commit 配置:
pre-commit:
commands:
hugo-template-test:
glob: "layouts/**/*.html"
run: |
timeout 20 npx hugo server --port 1315 2>&1 | grep -E "error|Error" && exit 1 || exit 0
pkill -f "hugo server --port 1315" 2>/dev/null
GitHub Actions 工作流程
- name: Test Hugo templates
run: |
npx hugo server --port 1315 &
sleep 10
curl -f http://localhost:1315/ || exit 1
pkill -f hugo
快速參考
| 動作 | 指令 |
|---|---|
| 測試模板(執行時期) | npx hugo server --port 1315 2>&1 | head -50 |
| 僅建置(不充分) | npx hugo --quiet |
| 檢查特定頁面 | curl -s -o /dev/null -w "%{http_code}" http://localhost:1315/path/ |
| 停止測試伺服器 | pkill -f "hugo server --port 1315" |
| 偵錯資料存取 | <pre>{{ printf "%#v" $var }}</pre> |
切記
- 永遠不要只依賴
npx hugo --quiet——它只檢查語法 - 一定要執行伺服器來測試模板變更
- 先檢查錯誤輸出再宣稱成功
- **使用
isset與index**進行安全的資料存取 - 含連字號的鍵值需要
index函式——點記號會失敗
相關資源
api-docs/README.md— API 文件工作流程、tags.yml 格式、覆蓋、產生管線- cypress-e2e-testing 技能 — UI 元件與頁面的 E2E 測試
- docs-cli-workflow 技能 — 建立/編輯文件內容
- ts-component-dev 代理 — TypeScript 元件行為與互動性
- ui-testing 代理 — 針對 UI 元件的 Cypress E2E 測試