Compare selection to categories

I have a list page with content from related pages that all have a number of categories assigned in their frontmatter. I want to show all content initially, but give the option to show only specific content based on user selection with Alpine.js. There are numerous examples online how this can be done, but I seem to fail at the point where I populate the categories and compare them to the user input.

The categories do show in the select dropdown. I can also get the individual pages’ categories as [category1 category2 category3], but I cannot manage to check if the selection equals/intersects/is in one of the categories of each page. (or am probably making more mistakes). Thank you for your help!

This is my code:

<div x-data="{ selected: 'placeholder' }">  
  <select x-model="selected">
    <option value="placeholder" selected disabled>Select</option>
    {{ $categories := $.Site.Taxonomies.categories.Alphabetical  }}
    {{ range $categories }}
    {{ if .Term }}   
    <option value=".category-{{ .Term }}" x-hide:selected="selected === .category-{{ .Term }}">{{ .Term }}</option>
    {{ end }}
    {{ end }}
  </select>
  {{ range .Pages }}
    <div x-show="selected == {{ .Params.Categories }}" x-cloak>
      <a href="{{ .RelPermalink }}">
        <img src="{{ .Params.coverimage }}">
        {{ .Title }}
      </a>
    </div>
  {{ end }}
</div>

I would very much appreciate if somebody could point me in the right direction here. This is my first time working with Hugo and Alpine, and I still could not figure it out. I also appreciate info on any other ways of achieving this. I do not want to use another framework like isotope.js and i would like to not reload the page (i do have taxonomy pages for specific terms available in my theme, but would like to apply the filter here by hiding certain elements with css). Thanks for any help!

Take this for a spin.

git clone --single-branch -b hugo-forum-topic-41678 https://github.com/jmooring/hugo-testing hugo-forum-topic-41678
cd hugo-forum-topic-41678
npm ci
hugo server
1 Like

This is amazing and does everything I needed. Thank you very much!

Thanks. It was a good opportunity for me to get my feet wet with Alpine. The tough part was figuring out how to wrangle the slice of terms into non-escaped JSON, and then slipping that into an HTML attribute.

I’m sure it’s possible, but would require some work… a multi-faceted filter for multiple taxonomies against the same list. Someday…

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