Hugo Show Related Posts By Tags

August 27, 2017

The following code will match posts with at least 1 similar tags.

{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
  {{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
  {{ if and $isMatchTags (ne .Permalink $currentPagePermalink) }}
    <a href="{{ .Permalink }}">{{ .Title }}</a>
  {{ end }}
{{ end }}

If you want to limit posts to a certain number.

{{ $.Scratch.Set "limit" 0 }}
{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
  {{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
  {{ if and $isMatchTags (ne .Permalink $currentPagePermalink) (lt ($.Scratch.Get "limit") 5) }}
    <a href="{{ .Permalink }}">{{ .Title }}</a>
    {{ $.Scratch.Add "limit" 1 }}
  {{ end }}
{{ end }}

The following code will achieve the following:

  • Find posts which matches at least 2 tags
  • If none is found, find posts with 1 tag match and limit to 5 posts only.
{{ $.Scratch.Set "count" 0 }}
{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{/* range (where .Site.Pages "Section" "tutorials") */}}
{{ range .Site.Pages }}
{{ $isMatchTags := intersect $tags .Params.tags | len | lt 1 }}
{{ if and $isMatchTags (ne .Permalink $currentPagePermalink) }}
  <a href="{{ .Permalink }}">{{ .Title }}</a>
  {{ $.Scratch.Add "count" 1 }}
{{ end }}
{{ end }}

{{ if eq ($.Scratch.Get "count") 0 }}
  {{ $.Scratch.Set "limit" 0 }}
  {{/* range (where .Site.Pages "Section" "tutorials") */}}
  {{ range .Site.Pages }}
  {{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
  {{ if and $isMatchTags (ne .Permalink $currentPagePermalink) (lt ($.Scratch.Get "limit") 5) }}
    <a href="{{ .Permalink }}">{{ .Title }}</a>
    {{ $.Scratch.Add "limit" 1 }}
  {{ end }}
  {{ end }}
{{ end }}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.