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 …
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.
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?