How to count multiple products in range?

I have a list of products and each product has one or many keywords. I would like to count how many products their are for a few specific keywords.

My product front matter looks like this:

title = "Product 1"
keywords = ["Wood", "Green", "Blue"]

title = "Product 2"
keywords = ["Aluminium", "Orange", "Green"]

title = "Product 3"
keywords = ["Wood", "Brown"]

In my example, I’d like to know how many products have the keywords “Wood”, “Orange”, “Green”, and “Blue”. What’s the best way to solve this?

A normal counter for all pages would be

{{$counter := 0}}
{{range .RegularPages}}
{{$counter := add $counter 1}}

The alternative that I can think of is to use a if/else statement for each, like so:

{{$counterGreen := 0}}
{{range .RegularPages}}
{{if in .Keywords "Green"))
{{$counterGreen := add $counterGreen 1}}

Is there a better way?

I’m also wondering how I should keep track of what keyword has what number to keep things DRY as I want to be able to do:

There are n products that are Green.

Perhaps the use of a dict?

If you can, I would suggest configuring keywords as taxonomies. This would make it a lot easier to figure out how many products have keyword foo and what these products are.


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