Hugo テンプレート開発スキル
目的
このスキルは、静的ビルドでは見逃されるエラーを捕捉するための必須ランタイムテストを含む、適切な Hugo テンプレート開発プラクティスを強制します。
重要なテスト要件
Hugo の npx hugo --quiet はテンプレートの構文のみを検証し、ランタイム実行は検証しません。
未定義フィールドへのアクセス、nil 値、不正な型アサーションなどのテンプレートエラーは、Hugo が実際にページをレンダリングするときにのみ現れます。テンプレートの変更は、必ずサーバーを実行してテストしなければなりません。
必須テストプロトコル
Hugo テンプレートを変更する場合
layouts/、layouts/partials/、または layouts/shortcodes/ 内のファイルを変更した後:
ステップ 1: 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/" と表示すること
エラーが発生した場合: テンプレートを修正し、先に進む前にステップ 1 を繰り返してください。
ステップ 2: ページがレンダリングされることを確認する
curl -s -o /dev/null -w "%{http_code}" http://localhost:1315/PATH/TO/PAGE/
期待される結果: HTTP 200 ステータスコード
ステップ 3: ブラウザテスト(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 エラーを捕捉できます。
ステップ 4: テストサーバーを停止する
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. 空マップ vs 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 固有のパーシャル
├── shortcodes/ # コンテンツ用ショートコード
└── TYPE/ # タイプ固有のテンプレート (api/ など)
└── single.html # 単一ページテンプレート
パーシャル命名規則
- 説明的な名前を使用:
api/sidebar-nav.html、nav.htmlは避ける - 関連するパーシャルはサブディレクトリにグループ化する
- 目的と必要なコンテキストを説明するコメントを先頭に含める
関心の分離: テンプレート 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 | 表示/非表示、クラスのトグル |
アンチパターン: テンプレート内のインライン 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,
// ... その他のコンポーネント
};
データ受け渡しパターン
Hugo データは data-* 属性を介して 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 ページレイアウト(3カラム、サイドバー、TOC)
└── _api-operations.scss # オペレーションレンダリング(メソッド、パラメータ、レスポンス)
TypeScript コンポーネントチェックリスト
新しいインタラクティブ機能を作成する場合:
-
assets/js/components/に TypeScript ファイルを作成 - コンポーネントオプションのインターフェースを定義
- デフォルトの初期化関数をエクスポート
-
main.jsの componentRegistry に登録 - HTML 要素に
data-component属性を追加 -
data-*属性を介してデータを渡す(インライン JS は使用しない) - テンプレート内にインライン
<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 との統合
プリコミットフック(推奨)
.lefthook.yml またはプリコミット設定に追加:
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 テスト