Loop through all tags in a particular category

Hello,

I have tags Tag1, Tag2, Tag3
across categories Cat1, Cat2, Cat3.

I want to loop through to find all the Titles of the Articles which are under Category1 and various tags. So in essence, I am looking for articles filtered like below:

- - - For Cat1 - - -

- - Tag1 
Article a, Article c, Article f

- - Tag2 
Article e, Article b,

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

- - - For Cat2 - - - 

- - Tag1 - - 
Article m, Article n

...etc

So essentially I have several category pages and in each category page I want to segregate all the tags separately and show the posts which match that category and that tag. Hope I was able to describe clearly.

Please help. I am new to ranges and where functions and unable to find the right solution. Thanks.

Short Answer

layouts/term/category.html:

{{/* Create a sorted slice of tags present in the listed pages. */}}
{{ $tags := slice }}
{{ range .Pages }}
  {{ $tags = $tags | append .Params.tags }}
{{ end }}
{{ $tags = $tags | uniq | sort }}

{{/* Range through the tags, then range through the pages that contain that tag. */}}
{{ $pages := .Pages }}
{{ range $tags }}
  <hr>
  <h2>{{ . }}</h2>
  {{ range (where $pages ".Params.tags" "intersect" (slice .)).ByTitle }}
    <h3><a href="{{ .RelPermalink }}">{{ .Title }}</a></h3>
  {{ end }}
{{ end }}

Long Answer

The template lookup order is an important factor. You want to make sure that your listing of pages under a particular category does not clobber the list of pages under a particular tag. See:

Try this:

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

@jmooring: It works perfectly. Thanks very much :slight_smile:

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