Show Related Posts in Hugo

Hugo is a great tool for blogging, creating quick and automated posts. As part of a blog, you will sometimes want to show related articles and posts to the one you’re reading. This is what this post sets out to achieve.

We can make this in Hugo easily if we are using it’s tags structure. With this in mind, you’ll need to be listing tags within your markdown for this to work.

Then all you have to do is use some code like below in your layout.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{{- range first 1 (where (where .Site.Pages ".Params.tags" "intersect" .Params.tags) "Permalink" "!=" .Permalink) -}}
    {{- $.Scratch.Set "has_related" true -}}
{{- end -}}

{{ if $.Scratch.Get "has_related" }}
    <div class="related-content">
        <h3>Related Posts</h3>
        <ul>
            {{- $num_to_show := .Site.Params.related_content_limit | default 3 -}}
            {{ range first $num_to_show (where (where .Site.Pages ".Params.tags" "intersect" .Params.tags) "Permalink" "!=" .Permalink) }}
            <li>
                <a href="{{ .RelPermalink }}">{{ .Title }}</a>
                &ndash; 
                <time datetime="{{ .Date.UTC.Format "2006-01-02T15:04:05-0700" }}">
                    {{ .Date.Format "Jan 2, 2006" }}
                </time>
                <br> 
                <small>{{ .Summary | plainify | htmlUnescape }}</small>
            </li>
          {{ end }}
        </ul>
    </div>
{{ end }}

It will match up pages based on common tags and will show the three most likely. You can change the number it shows on line 9 if required.

It also currently displays a title, the post’s date and it’s summary.

This should then end up looking like this:

preview of related posts in hugo

This code has been adapted from a comment on Hugo’s discourse.