Generating Archive Pages with Hugo
In the absence of a search engine — an
There are a few requirements. The archive pages should be a bit modular. We
should be able to just drop an archive.md file into any folder within the
content directory and generate a single archive page for that topic.
text
hugo
|__ content
|__ posts
|__ archive.md
projects
|__ archive.mdWe should be able to generate clean slugs. Hugo makes that
URLs are typically generated according
to the file directory structure.
/posts/archive and /projects/archive.
We could also take a more pragmatic approach by using the following file
directory structure which results in slugs like /archives/posts or
/archives/projects.
text
hugo
|__ content
|__ archives
|__ posts.md
|__ projects.mdThe content of each archive page will be determined by the parameters within the
front matter, particularly the layout parameter. The front
posts/archive.md will contain
the needed parameters to generate that page.
yaml
---
title: "Posts Archive"
layout: archive
hidden: true
type: posts
summary: This page contains an archive of all posts.
---The layout parameter will reference the template
layouts/_default/archive.html to render a single archive page. That template
file is shown below.
html
{{ define "main" }}
<section>
{{ $type := .Type }}
{{ $.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 }}This template groups all posts for a particular topic by year and orders them by
the month, taking into account the type parameter from the front matter of
archive.md. Note the use of the .Scratch
There are quirks when implementing an archive page as a single post. We may want
to adjust the RSS and pagination templates to hide additional data produced by
an archive page with the hidden: true attribute.