Related content specific to section

I’ve looked through the docs on Related Content, and I’ve got it to work, but I was wondering if there’s a better way of finding related content for a page that belongs to a specific section.

In my front matter across sections, I use the parameter Keywords. In books/single.html, I would like to display the first 6 related posts from content/books. I can do so as follows:

{{$related := (where site.RegularPages "Section" .Section).Related .}}
{{with $related}}
  {{range $i, $e := first 6 .}}
    {{.Title}}
  {{end}}
{{end}}

I use the where statement as otherwise, the related function picks up content from other sections that have the same Keyword. But there’s quite a performance hit from including the where statement.

If I do:

{{$related := .Site.RegularPages.Related . | first 6}}
{{with $related}}
  {{range $i, $e := .}}
    {{.Title}}
  {{end}}
{{end}}

I get related content from the books section as well as from other sections, but the difference in performance is significant, from a 50 second build time down to 4 seconds.

Is there a better way of getting related content for a single page from the section it belongs to rather than using the where statement as in my first example? Many thanks.

EDIT

I figured out one way to solve this: create a custom index and then use the second code snippet, but not sure if this is the recommended approach.

I think a more performant variant of the above would be:

{{$related := .CurrentSection.RegularPages.Related .}}

You can also do:

{{$related := .CurrentSection.RegularPagesRecursive.Related .}}

Also, if you have expensive operations that you do again and again, partialCached is your friend. Rememeber: it can return values.

Edit in: I think the equivalent to your first where clause would be

{{$related := .FirstSection.RegularPagesRecursive.Related .}}

2 Likes

This is great. Thanks bep!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.