Blog Updates: Series

June 17, 2019

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.


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>{{$series | humanize}} Series</h3>
        {{ range $ind,$post := $.Site.Pages.ByDate}}
        {{ if eq $post.Params.series $series }}
            {{ if eq $post.Permalink $.Page.Permalink}}
            <strong>{{ $post.Params.title }}</strong>
            {{ else }}
            <a href="{{ $post.RelPermalink }}">{{ $post.Params.title }}</a>
            {{ end }}
        {{ end }}
        {{ end }}
{{ end }}

The partial above above attempts to find a page parameter series and if it exists it loops through all the pages in the site. A 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" . }}
    {{ partial "footer" . }}

Notice “the dot” (.) in the partial function, this passes in contextual variables to the series partial and without it nothing will display.

See Also

Last Updated: 2019-06-23 21:52