DEV Community

Zak Miller
Zak Miller

Posted on • Originally published at zakmiller.com

1 2

Hugo - How to Filter Posts With a Tag

#go

While recently working on a website, I wanted to display a subset of my posts based on a particular tag. I hadn't had any prior experience with the go templating engine, so this took me a bit longer to figure out than I'd care to admit, so I thought I'd share it with all of you.

This example applies anytime you want to filter any list of pages with a taxonomy.

    <ul>
      {{ range where .Paginator.Pages ".Params.tags" "intersect" (slice "popular")}}
      <li>
        <span>{{ .Date.Format (.Site.Params.dateFormat | default "January 2, 2006" ) }}</span>
        <a href="{{ .URL }}">{{ .Title }}</a>
      </li>
      {{ end }}
    </ul>

The first line is really all that matters. We're range-ing over the pages, grabbing the tags from each of those pages and seeing if they intersect with a new slice that only contains popular.

A contains operator is what I would expect to use here, but as far as I can tell there isn't one, so you have to use this intersect workaround.

I hope that was helpful! If you have any questions please let me know.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay