Suggesting related content in Hugo

Posted: | Updated: | Tags: til webdev

It has been 87 days since I enabled the ability to show related content at the bottom of each post on this blog, aptly titled “Related ramblings”. This uses Hugo’s built-in Related Content functionality. If you use a pre-made theme you may never directly work with this feature. I wanted to highlight how easy it was to use and how impressed and I am with the results.

To enable my theme to use this features, I simply had to create a new partial that could be used in my post template. The following snippet uses .Related which takes the current page and finds every related page according to the related configuration. The first 5 are picked and rendered onto the page by referencing this partial. To view the code you can refer to the commit on the theme.

<div>
    {{ $related := .Site.RegularPages.Related . | first 5 }}
    {{ with $related }}
        <h3>Related ramblings</h3>
        <ul>
            {{ range . }}
                <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
            {{ end }}
        </ul>
    {{ end }}
</div>

A great benefit of using this is that Hugo provides the users many parameters to fine tune the algorithm used to show related content. By default, according to the documentation, the related pages are picked according to the keywords, date and tags parameters in the posts frontmatter, they are weighted 100, 10 and 80 accordingly. It’s important to also note that Hugo does not index any of the page’s content. Even though I don’t use keywords in any of my Pages, Hugo still performed very well just relying on the date and tags for each of my 45 posts.

Over the last week and moving forward I’ll be playing around with these configurations a bit to see if I can get any small improvements.


Related ramblings