Show a list of related content

I’m trying to create a list of related content. After checking the documentation, I did manage to get a complete list of all the posts that share at least one category with the post the user is currently viewing.

{{ $page_link := .Permalink }}
 {{ $categories := .Params.categories }}
  {{ range $page := .Site.Pages }}
  {{ $has_common_categories := intersect $categories .Params.categories | len | lt 0 }}
  {{ if and $has_common_categories (ne $page_link $page.Permalink) }}
  <li><a href="{{ $page.Permalink }}">{{ $page.Title }}</a></li>
  {{ end }}
{{ end }}

Now what I need to achieve is limit that to just the first 5 items of the list; adding a “first 5” in the range won’t work since it will limit the matching categories for just the first five posts…

I don’t think there is any break in Go templates, but you should be able to do this with a counter and only print the link for the first 5. I guess you would have to use Scratch for that.

And I guess some solid “related content” is a feature that Hugo should have some native support for, soon …

I´ll check it out, never used the counter before.

bep, big thanks for your help; here is the solution:

{{ $page_link := .Permalink }}
{{ $categories := .Params.categories }}
{{ $c := 0 }}
{{ range $page := .Site.Pages }}
{{ $has_common_categories := intersect $categories .Params.categories | len | lt 0 }}
{{ if and $has_common_categories (ne $page_link $page.Permalink) (lt ($.Scratch.Get "$c") 5)}}
{{ $.Scratch.Add "$c" 1 }}
<li><a href="{{ $page.Permalink }}">{{ $page.Title }}</a></li>
{{ end }}
{{ end }}

Just a detail, but may be important to understand in other situations: The keys used in scratch have nothing to do with the variables declared on the outside. Think of Scratch as a map/dictionary.

So the above line can be safely deleted.

Ok, let’s change it up then so the solution is clear

3 Likes

Sorry to resurrect this old one. If I wanted to make that 5 (to show only five related content) a variable, definable in config.toml, how can that be done?

Try this:

{{ $num_to_show := .Site.Params.related_links_limit | default 5 }}

Then you replace the number 5 in code snippet above with $num_to_show.

In config.toml file, put related_links_limit = 10 or whatever under [Params] section, otherwise, it’ll be 5 by default.

1 Like