Contents
This blog hadn’t had a redesign for a decade. It ran on a self-made CMS, which by now was outdated, to put it mildly. So at some point I was ready for a remake. My first move was to look for a CMS, or a headless CMS. Then it dawned on me that the blog is actually static. There are no forms and no services here, it’s all about presenting content. So why not go with a site generator? With no server-side code it’s far more secure and reliable. It’s obviously faster. And, as it turned out, it gives you more freedom and flexibility.
I looked at Jekyll, Gatsby, 11ty and Hugo. Despite my strong React background I went with Hugo, which is written in Go. Man, it is fast beyond any belief! What’s more, it has:
- great taxonomies
- decent SEO support
- predefined templates for Google Analytics, Disqus, Open Graph, Twitter Cards and more
- Hugo Pipes, with CSS preprocessing (SASS/PostCSS), asset minification (CSS, JS, JSON, HTML, SVG or XML), asset bundling and so on
- customizable rendering of Markdown elements
What impressed me most is that Hugo lets you create custom Markdown tags (shortcodes). For example, I use a custom img that resizes the image for every responsive breakpoint and generates an HTML img with a matching srcset.
As for the downsides, I had to learn the basics of the Go template package to get what I wanted. It turned out to be quite an elegant language, though. The documentation is detailed, but a newcomer may still struggle. So here’s my own experience of rebuilding the blog with Hugo.
Objectives
So what are we building? A plain blog with a home page listing the posts:
The sidebar shows the available categories. Each of them leads to a filtered listing:
The post page has previous/next navigation links:
And, as an example of a plain site page, there’s “About”:
Installing
Installation is explained well in the documentation. Hugo is available for macOS, Windows, Linux, OpenBSD and FreeBSD. On Ubuntu I used snap:
snap install hugo --channel=extended
Note the extended. That’s the version with Sass/SCSS support.
Getting started
Let’s create a new project named blog:
hugo new site blog
Inside the created directory
cd blog
we find the following structure:
.
├── archetypes
│ └── default.md
├── config.toml
├── content
├── data
├── layouts
├── resources
├── static
└── themes
Here’s what goes where:
- archetypes: templates for new content created with the CLI
- assets: any files you want to process with Hugo Pipes
- config: instead of a single site config file, you can build an environment-specific configuration structure here
- content: Markdown files with the site content, split into section directories
- data: besides content, you can generate pages from plain data (YAML, JSON or TOML)
- layouts: layout templates, based on Go HTML templates
- static: static files like images, CSS or JavaScript that site pages access directly, without any transformation
There’s also config.toml, the root site config (newer Hugo versions name it hugo.toml). Hugo supports YAML, JSON and TOML. I find YAML the cleaner format, so I replaced config.toml with a config.yaml:
baseURL: "http://localhost:1313/"
languageCode: en-us
title: Blog
I took
localhost:1313because it’s the default for LiveReload. For a build you can set it on the command line, likehugo -b http://myblog.dev
Content
You can create a content blank with the CLI. Hugo then creates a file like content/posts/lorem-ipsum.md with metadata prefilled from the matching archetype.
I’d rather create content/posts/lorem-ipsum/index.md by hand, though. Here lorem-ipsum is the slug, so the page is available at /posts/lorem-ipsum. That way every page gets its own folder, and its resources (images and so on) live right next to it.
The first content page, content/posts/lorem-ipsum/index.md, may look like this:
---
title: "Lorem ipsum dolor sit amet"
date: 2020-03-04T13:40:25+01:00
draft: false
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam nisl mauris, dictum vel molestie nec, efficitur non arcu. "
coverImage: main.png
categories: [ "bar" ]
images: [ "/posts/lorem-ipsum/main.png" ]
---
Lorem ipsum dolor sit amet, ...
The metadata block at the top is called front matter. It’s enclosed in ---, which means YAML. The fields:
- title: the page title
- date: the creation date (used for sorting)
- draft: marks the page as a draft
- description: the page description, used as the summary in listings and for SEO
- coverImage: a custom field for the cover image
- categories: the categories the page belongs to
- images: images for Open Graph
In the same way we create a second page, content/posts/fusce-eu-congue-dolor/index.md, and the About section page, content/about/_index.md.
content/about/_index.md
---
title: "About"
date: 2020-03-04T13:40:25+01:00
draft: false
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam nisl mauris, dictum vel molestie nec, efficitur non arcu. "
categories: [ ]
---
Lorem ipsum dolor sit amet, consectetur adipiscing elit...
Layouts
We have four page types: home page, post page, About page and category page. Plus a 404 Page Not Found. The top-level layouts look like this:
layouts
├── 404.html
├── about
│ └── section.html
├── _default
│ └── category.html
├── index.html
└── posts
├── section.html
└── single.html
layouts/index.html: the home pagelayouts/404.html: 404 Page Not Foundlayouts/about/section.html: the About page (the index of the about section, at/about)layouts/posts/section.html: the index of the posts section, at/posts(here just a copy of the home page layout)layouts/posts/single.html: a post, at/posts/<slug>layouts/_default/category.html: a category, atcategories/<category>
Home page layout#
Let’s start with the home page:
layouts/index.html
{{ partial "header.html" . }}
<body>
<div class="container">
{{ partial "navbar.html" . }}
<main class="main">
{{ partial "posts.html" . }}
{{ partial "sidebar.html" . }}
</main>
{{ partial "footer.html" . }}
</div>
</body>
</html>
The partial function includes sub-templates. The header comes first:
layouts/partials/header.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="description" content="{{ .Description }}">
<link rel="canonical" href="{{ .Permalink }}">
<title>{{ .Title }}</title>
{{ template "_internal/opengraph.html" . }}
{{ template "_internal/twitter_cards.html" . }}
{{ $styles := resources.Get "css/index.css" | minify | fingerprint }}
<link href="{{ $styles.Permalink }}" rel="stylesheet">
</head>
.Title and .Description hold the values from the front matter. .Permalink is the permanent link to the page.
Then we include the internal templates for Open Graph and Twitter Cards.
Next, Hugo Pipes minify and fingerprint our CSS from assets/css/index.css (resources.Get looks in the assets directory):
{{ $styles := resources.Get "css/index.css" | minify | fingerprint }}
<link href="{{ $styles.Permalink }}" rel="stylesheet">
The fingerprint goes into the file name, so browsers can cache the file forever and still get the new version after a change. It also computes an SRI hash, available as $styles.Data.Integrity if you want to add an integrity attribute. You can add SASS preprocessing and PostCSS postprocessing to the same pipe.
layouts/partials/navbar.html
<header class="header">
<nav class="main-nav">
<a class="{{ if or (.Page.IsHome) (eq .Section "posts") }}is-active{{ end }}" href="/" ><span>Blog</span></a>
<a class="{{ if eq .Section "about" }}is-active{{ end }}" href="/about" ><span>About me</span></a>
</nav>
</header>
The navbar links to the section pages and uses conditions to highlight the current section. Alternatively, you can use a menu.
layouts/partials/posts.html
<div class="posts">
{{ range .Paginator.Pages.ByDate.Reverse }}
{{ .Render "article-card" }}
{{ end }}
{{ template "_internal/pagination.html" . }}
</div>
To render the listing, we iterate over the .Paginator.Pages collection, sorted by date and reversed, so the newest posts come first. Strictly speaking, this sorts only the posts on the current page. Hugo already orders pages newest first by default, so here it changes nothing. If you need a different order across all pages, pass the sorted list to .Paginate instead.
The post card lives in layouts/_default/article-card.html. It’s a content view, a type of template meant for repeating content.
At the end we include the internal pagination template.
layouts/_default/article-card.html
<article class="card__article">
<h2 class="card__title"><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2>
<div class="card__meta">
<time>{{ .Date.Format "January 2, 2006" }}</time>
</div>
<div class="summary">
<figure>
<img itemprop="image" src="{{ .RelPermalink }}/{{ .Params.coverImage }}" alt="{{ .Title }}" />
</figure>
<p>
{{ .Description | html }}
</p>
</div>
</article>
The card refers to the front matter fields. .Date gets formatted, and .Description is rendered as HTML, without escaping.
What about the cover image? We could simply put images into static/img and access them as /img/image.jpg. Keeping them as page resources next to the content file has advantages, though. You’ll see them in the “Responsive images” section.
layouts/partials/sidebar.html
<aside class="sidebar">
<article>
<h2>Labels</h2>
<nav class="category-list">
{{- range $name, $taxonomy := $.Site.Taxonomies.categories }}
{{- with $.Site.GetPage (printf "/categories/%s" $name) }}
<a href="{{ .Permalink }}" class="category-list__li">
{{ .Page.Title }} <span class="category-list__count">({{ $taxonomy.Count}})</span>
</a>
{{- end }}
{{- end }}
</nav>
</article>
</aside>
Hugo supports flexible grouping of content with taxonomies. You can group content by categories, series, tags and so on. Every page with a categories list in its front matter gets indexed, so $.Site.Taxonomies.categories gives us the full list of categories.
layouts/partials/footer.html
<footer class="footer">
footer
</footer>
Post layout#
layouts/posts/single.html
{{ partial "header.html" . }}
<body>
<div class="container">
{{ partial "navbar.html" . }}
<main class="main">
<div>
<article class="single">
<h2 class="card__title">{{ .Title }}</h2>
<div class="card__meta">
<time>{{ .Date.Format "January 2, 2006" }}</time>
</div>
<figure>
<img itemprop="image"
src="{{ .RelPermalink }}/{{ .Params.coverImage }}"
alt="{{ .Title }}" />
</figure>
{{ .Content }}
</article>
<nav class="page-nav">
{{with .PrevInSection}}
<a class="btn btn-default" href="{{.Permalink}}">
Previous:
<span>{{ .Title }}</span>
</a>
{{end}}
{{with .NextInSection}}
<a class="btn btn-default" href="{{.Permalink}}">
Next: <span>{{ .Title }}</span>
</a>
{{end}}
</nav>
</div>
</main>
{{ partial "footer.html" . }}
</div>
</body>
</html>
The content renders much like in layouts/_default/article-card.html. What’s new is .PrevInSection and .NextInSection, the neighboring pages in the section. If the template logic looks cryptic, here’s how with works. Say we have an object .Foo with a property .Bar, and we want to render .Foo.Bar:
{{with .Foo }}
{{ .Bar }}
{{end}}
If .Foo exists, the block renders with .Foo as its context. If it doesn’t, nothing renders, which is exactly what we want for the first and the last post.
About page layout#
layouts/about/section.html
{{ partial "header.html" . }}
<body>
<div class="container">
{{ partial "navbar.html" . }}
<main class="main">
<div>
{{ .Content }}
</div>
</main>
{{ partial "footer.html" . }}
</div>
</body>
</html>
Category layout#
layouts/_default/category.html
{{ partial "header.html" . }}
<body>
<div class="container">
{{ partial "navbar.html" . }}
<main class="main">
<div class="posts">
<h2 class="category">Items in category <b>{{ .Title | lower }}</b></h2>
{{ range .Data.Pages }}
{{ .Render "article-card" }}
{{ end}}
</div>
{{ partial "sidebar.html" . }}
</main>
{{ partial "footer.html" . }}
</div>
</body>
</html>
In the end, the layouts directory looks like this:
layouts
├── 404.html
├── about
│ └── section.html
├── _default
│ ├── article-card.html
│ ├── category.html
│ └── terms.html
├── index.html
├── partials
│ ├── categories.html
│ ├── footer.html
│ ├── header.html
│ ├── navbar.html
│ ├── posts.html
│ └── sidebar.html
└── posts
├── section.html
└── single.html
Extras#
Search engines and feed readers want RSS, a sitemap and robots.txt, so let’s copy the templates from the docs: RSS, sitemap, robots.txt.
layouts
├── ...
├── robots.txt
├── rss.xml
└── sitemap.xml
We also extend layouts/partials/header.html with this:
{{ with .OutputFormats.Get "rss" -}}
{{ printf `<link rel="%s" type="%s" href="%s" title="%s" />` .Rel .MediaType.Type .Permalink $.Site.Title | safeHTML }}
{{ end -}}
which adds:
<link rel="alternate" type="application/rss+xml" href="https://example.com/index.xml" title="Site Title">
Building and running
Now we can start the Hugo server with LiveReload:
hugo server --buildDrafts --disableFastRender
and open the blog at http://localhost:1313/.
While the server is running, any change to content, layouts or CSS shows up right away in the open pages.
To build for deployment:
hugo -b https://example.com
Unlike the dev server above, leave out --buildDrafts (-D) here, otherwise your drafts get published.
Responsive images
For the best user experience we want responsive images. Say the content column is at most 680px wide, so images are never wider than that. But we also support Retina screens with a pixel density of 2x, so the source images have to be 1360px wide. The browser should load the image that fits the device best, down to a 414px version for small phones.
In layouts we can use this snippet:
{{.Scratch.Set "src" (.Resources.GetMatch (printf "*%s*" .Params.coverImage)) }}
{{ $src := .Scratch.Get "src" }}
{{ .Scratch.Set "small" ($src.Resize "414x") }}
{{ .Scratch.Set "medium" ($src.Resize "680x") }}
{{ $small := .Scratch.Get "small" }}
{{ $medium := .Scratch.Get "medium" }}
<img
itemprop="image"
sizes="(max-width: 414px) 414px, 680px"
srcset="{{ $small.RelPermalink }} 414w, {{ $medium.RelPermalink }} 680w, {{ $src.RelPermalink }} 1360w"
alt="{{ .Title }}" />
We look up the cover image among the page resources and keep the original (1360px) in $src. Then we resize it to 414px wide and keep that in $small, and do the same for 680px in $medium. Their links (e.g. $small.RelPermalink) go into the srcset.
Every candidate in srcset has a width descriptor, the original included (1360w). The HTML spec doesn’t allow mixing width descriptors with a density descriptor like 2x. With widths only, the browser does the math: a 680px slot on a 2x screen needs 1360 pixels, so it picks the original. By the way, the .Scratch round trip isn’t really needed. Plain template variables ({{ $small := $src.Resize "414x" }}) do the same.
Nice, but what about images inside the content? Here we can extend Markdown with shortcodes. I’d like a shortcode for responsive images that works like this:
{{< img src="example.png" alt="Example" >}}
For that we create shortcodes/img.html with the same content as the layout snippet above, except these lines:
{{.Scratch.Set "src" (.Resources.GetMatch (printf "*%s*" (.Get "src"))) }}
...
<img
...
alt="{{ .Get "alt" }}" />
Instead of taking the image and alt text from the front matter, the shortcode reads them from its own attributes.
Was it worth it?
Absolutely. Hugo is lightning fast. With LiveReload running, you can’t even tell when it rebuilds. It’s a mature site generator, and it seems the developers have thought of nearly everything. Shortcodes and Markdown render hooks give you a lot of freedom, and Hugo Pipes handle the whole asset pipeline without any tool besides Hugo. Go templates take some getting used to, but I really enjoy working with it.