Hugoでブログ記事一覧ページ(ブログアーカイブページ)を作成する
更新日:2022.07.02
作成日:2020.12.26
以前、ブログメンタリングを受講していたときの課題でもあった「アーカイブページ」を作った時のメモです。 ようやく、ブログ記事一覧の機能を実装できました。
実装方法
Hugoでのアーカイブページの作り方を調べてみると、大きく分けて次の2つがありました。
- a) Taxonomyでコンテンツごとに年・月の情報を付加する
- /2020/, /2020-12/のように年ごと、月ごとのアーカイブページを自動生成できる
- b) Archive用のテンプレートと、Archiveページのコンテンツを作成する
a)の方式だと各コンテンツのFront Matterに情報を付加しないといけないため、まずは簡単にできそうなb)の方法で実装しました。
layouts/_default/archive.html
{{ define "main" }}
<article class="mx-4 sm:mx-12">
<section class="">
<div class="">
<h2 class="font-bold text-xl">Blog Archives</h2>
{{ $type := "blog" }}
{{ $isGroupKey := true}}
{{ range (.Site.RegularPages.GroupByDate "2006") }}
{{ $count := (len .Pages) }}
{{ if (gt .Key 2000) }}
{{ range (where .Pages "Type" $type) }}
{{ if $isGroupKey }}
<h1 class="font-bold mt-2">{{ .Date.Format "2006" }}年 ({{ $count }})</h1>
{{ $isGroupKey = false}}
{{ end }}
{{ end }}
{{ $isGroupKey = true}}
<ul class="">
{{ range (where .Pages "Type" $type) }}
<li>
<a class="" href="{{ .RelPermalink }}">
<span class="">{{ .Date.Format "01/02" }}</span> — {{ .Title }}
</a>
</li>
{{ end }}
</ul>
<br>
{{ end }}
{{ end }}
</div>
</section>
<section>
<div class="mt-8">
{{- partial "share.html" . -}}
</div>
</section>
</article>
{{ end }}
content/blog/archives/index.md
---
title: "Blog Archive"
layout: archive
slug: archives
---
.Site.RegularPages.GroupByDate "2006"
で年ごとにグルーピングされたリストを取得できます。
if (gt .Key 2000)
としているのは、このcontent/blog/archives/index.md
自体がアーカイブページへ表示されないようにするためです。
(index.md
ではコンテンツの日付を指定していないため、0年として表示される)
参考ページ
- Generating Archive Pages with Hugo - Thedro Neely
- 今回の実装例
- Inconvenient Hugo Yearly/Monthly Archives - Melcher.dev
- Taxonomyでの実装例
合わせて読みたい
Related contents

TECH
2020.11.01
HugoでTailwindCSSを利用しAMP Validなページを生成する

TECH
2020.03.13
npm-run-allでローカルAPI serverとHugo serverを同時に実行する

TECH
2020.02.02
HugoでAMP対応のブログカードを作る

TECH
2023.02.03
Hugo v0.109.0でパンくずリストをシンプルに実装する

TECH
2022.09.03
【Hugo】Render Hooks for Code Blocksを利用してコードブロックにファイル名を表示する

TECH
2022.08.29
Hugoでブログカードを作成する(resources.GetRemote利用)

TECH
2022.08.14
GitHub PagesからCloudflare Pagesへの移行

TECH
2022.06.29
AMP Service WorkerでPrefetch Linksを実現する