Blog Post Archive With Hugo
I took this code from The Drone Ely’s blog.
First, I created a file layouts/_default/archive.html with the following contents:
{{ define "main" }}
<section>
{{ $type := "posts" }}
{{ $.Scratch.Set "count" 1 }}
{{ range (.Site.RegularPages.GroupByDate "2006") }}
{{ if and (gt .Key 1) (gt (where .Pages "Type" $type) 0) }}
{{ range (where .Pages "Type" $type) }}
{{ if (eq ($.Scratch.Get "count") 1) }}
{{ $.Scratch.Set "count" 0 }}
<h1> {{ .Date.Format "2006" }}</h1>
{{ end }}
{{ end }}
{{ $.Scratch.Set "count" 1 }}
<ul>
{{ range (where .Pages "Type" $type) }}
{{ if (ne .Params.hidden true) }}
<li>
<a href="{{ .RelPermalink }}">
<span>{{ .Date.Format "02 Jan" }}</span> — {{ .Title }}
</a>
</li>
{{ end }}
{{ end }}
</ul>
{{ end }}
{{ end }}
</section>
{{ end }}
Then, I created a page named “archive” with:
hugo new archive.md
ARCHIVETXT=$(cat << EOL
---
title: "List of Blog Posts"
date: 2023-03-14T02:11:09+03:00
type: pages
layout: archive
---
This is a listing of blog posts
EOL
)
echo "$ARCHIVETXT" > content/archive.md
The link to the archive page had to be added to the site footer, so I put a link to /archive
into the file layout/partials/site-footer.html
.