Best Way to Group Cars by KM Range Without Repeating Loop in Hugo

How to Loop All Cars Once and Create KM Range Pages in Hugo?

My Situation

I have a car website made with Hugo.

I created different KM range pages like:

  • /km-driven/0-to-25k/
  • /km-driven/25k-to-50k/
  • /km-driven/50k-to-75k/
  • /km-driven/above-75k/

Each page filters cars based on distance driven.

Problem

Right now, every range page loops through all cars again to filter them.

So if I have 4 range pages, Hugo loops through all cars 4 times during build.

I have around 200–500 car pages.

I feel this may not be efficient.

What I Want

I want to:

  • Loop through all cars only one time
  • Group them into KM ranges
  • Then let each range page use its grouped cars

Can We Use Taxonomy for KM Ranges?

Can we use taxonomy for KM ranges?

Right now, I only have km-driven as a number in front matter.

I do not store the KM range (like 0–25k, 25k–50k) inside the car markdown file.

If I use taxonomy for ranges, then I will need to:

  • Add a KM range field in every car file
  • Manually update that range whenever I change the km-driven value

For example:

If I change KM from 24,000 to 26,000,
then I must also change the range from 0-25k to 25k-50k.

This means double work and possible mistakes.

So I am not sure if taxonomy is the correct solution.

Use where instead, which will be even faster with the next Hugo release. For example:

{{ $p := (site.GetPage "/cars").RegularPages }}
{{ $p = where $p "Params.km_driven" "ge" $.Params.km_driven.min }}
{{ $p = where $p "Params.km_driven" "le" $.Params.km_driven.max }}

Example:

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

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