Shortcode that lists all pages with same tag but excludes current one

I have just started with Hugo and am looking for a shortcut that does the following:

  • Lists all posts with the same tag but excludes the current page if tag is also assigned to the current page
  • Accepts a parameter $tagname to specify which tag is desired for the list

So far I have modified the links-to-all-tags.html example from the hugo docs website. Now i can use it with this syntax:
{{< list-post-by-tag $tag >}}

And this code seems to work but it also includes the current page:

{{ $pageName := index .Params 0 }}

{{ $tag := index .Params 0 }}
<ul class="{{ $tag }}">
    {{ with ($.Site.GetPage (printf "/%s" $tag)) }}
        {{ range .Pages }}
            <li><a href="{{ .Permalink }}">{{ .Title}}</a></li>
        {{ end }}
    {{ end }}
</ul>

What would be the best solution to exclude the current page from the ranges of pages that share the same tag?

Option 1 - Use the Related Content feature

{{ with $tag := .Get 0 }}
  {{ with site.RegularPages.RelatedTo (keyVals "tags" $tag) }}
    {{ with where . "Permalink" "ne" $.Page.Permalink }}
      <p>Related pages:
        <ul>
          {{ range . }}
            <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
          {{ end }}
        </ul>
      </p>
    {{ end }}
  {{ end }}
{{ else }}
  {{ errorf "The %q shortcode requires a single positional parameter. See %s" .Name .Position }}
{{ end }}

Option 2 - Where plus intersect

{{ with $tag := .Get 0 }}
  {{ with where site.RegularPages "Params.tags" "intersect" (slice $tag) }}
    {{ with where . "Permalink" "ne" $.Page.Permalink }}
      <p>Related pages:
        <ul>
          {{ range . }}
            <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
          {{ end }}
        </ul>
      </p>
    {{ end }}
  {{ end }}
{{ else }}
  {{ errorf "The %q shortcode requires a single positional parameter. See %s" .Name .Position }}
{{ end }}
4 Likes

Thank you very much. Option 2 was exactly what I was looking for.

I made a minor change to each of the approaches in my previous post to prevent rendering “Related pages” if the current page is the only page with the given tag.

1 Like

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