Blog Updates: Series
I’ve been using Hugo as my blog framework for a good while now and the reason I’ve stuck with it for so long is the freedom it gives me to tweak things to be exactly how I want. The series list I added this week is a good example of that.
Series
I recently decided for my trip to Japan I’d like to try and blog every day about what I’ve been up to. In order to group these posts together I wanted to be able to display a chronological list of all the entries in the series at the start of each post. As I wanted this to be set and forget - i.e. I shouldn’t need to remember to add a specific code to each post I decided the easiest way to solve this was using a Hugo partial template.
{{ $series := $.Page.Params.series}}
{{ if $series }}
<div class="series">
<h3>{{replace $series "-" " " | title}} Series</h3>
<ol>
{{ range $ind,$post := $.Site.Pages.ByDate}}
{{ if eq $post.Params.series $series }}
<li>
{{ if eq $post.Permalink $.Page.Permalink}}
<strong>{{ $post.Params.title }}</strong>
{{ else }}
<a href="{{ $post.RelPermalink }}">{{ $post.Params.title }}</a>
{{ end }}
</li>
{{ end }}
{{ end }}
</ol>
</div>
{{ end }}
The partial above attempts to find a page parameter series
and if it exists it loops through all the pages in the site. An unordered list is built up of each page where the series
matches the current page’s series
. If the current page permalink isn’t the same as the page’s permalink then the page appears as a link in the list - otherwise it appears as regular text as the user is currently on that page. Whilst it appears pretty verbose due to the nature of Hugo/Go templating the partial itself is simple enough.
In order to add the series partial to our blog theme we have to add it to layouts/partials/series.html
and then reference it from our single post partial as shown below.
{{ partial "header" . }}
<div class="theme-container no-sidebar">
{{ partial "nav" . }}
<section class="page">
<div class="content">
<h1 class="title">{{ .Title }}</h1>
<span class="date">{{ .PublishDate.Format "January 2, 2006" }}</span>
{{ partial "series" . }}
{{ .Content }}
{{ partial "related" . }}
</div>
{{ partial "footer" . }}
</section>
</div>
Notice “the dot” (.
) in the partial function, this passes in contextual variables to the series partial and without it nothing will display.