逆引きマニュアル: Hugo: テンプレートを1から作成する方法(最初だけ)

投稿日:

やりたいこと

テンプレートを1から作成する方法です。

前提条件

Hugo 0.40.2で動作確認しています。

概要

テーマによってはbaseof.htmlがなく、 single.htmlから{{ partial "header" }}のようにして設定するものもありますが、 全体の構造が分かりにくくなるため、baseof.htmlを作るのが良いです。

baseof.htmlを使うテンプレートは必ず、{{ define }}の定義が必要です。

Example Base Template Lookup Orderより、

The {{define}} block in this template tells Hugo that the template is an extension of a base template.

手順

まず、hugoBasicExample をクローンして、 hugo new themeコマンドでテーマを新規作成します。

# hugoBasicExampleのクローン
git clone https://github.com/gohugoio/hugoBasicExample.git
cd hugoBasicExample

# テーマの作成(例: 'simple'テーマ)
hugo new theme simple

すると、themes/simple ディレクトリに、テーマのスケルトンができます。 このディレクトリ以下に、次のようにファイルを追加編集します。

layouts/_default/baseof.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />

    <!-- Bootstrap CSS -->
    <title>{{ block "title" . }}{{ .Page.Title }} - {{ .Site.Title }}{{ end }}</title>
  </head>
  <body>
  </body>
</html>

layouts/_default/single.html および layouts/_default/list.html

{{ define "title" }}
{{ .Page.Title }} - {{ .Site.Title }}
{{ end }}

layouts/index.html

{{ define "title" }}
{{- .Site.Title -}}
{{ end }}

表示を確認します。hugoBasicExampleのトップディレクトリに移動して、 以下のコマンドを打ちます。

hugo serve -t テーマ名

以下のURLにアクセスして、中身が表示されたらOKです。

  • http://localhost:1313/about/
  • http://localhost:1313/post/creating-a-new-theme/

補足

外部サイト

マニュアル