GroupBy for Data Files


So I want to be able to use .GroupBy but for data files. It seems that .GroupBy is specific for pages. Any ideas on how I can do this?


I have a YAML data file full of locations. For each location, there’s a name, address, coordinates, phone number, etc. I want to list all locations out on a page, but group them by state.

To render groups of data files by a parameter contained in the data files themselves I use:

{{ $var := .Site.Data.<some-folder> }}
{{ range sort $var ".someParam" "desc"}}
{{ end }}

Obviously you can change the order by whatever you need by using i.e. asc

Thanks for that. Do you have a way to automate how .someParam is chosen?

If I used your example verbatim, I’d need to duplicate the range loop 53 times, one for each state and territory.

What is the actual form of these parameters? Are they nested inside a common parent parameter? Do these 53 parameters have anything in common?

If not I cannot see how you can render them in a terse way.

Yes the’re states.

Here’s an example of a data file I’d use:

- name: "Queens Library Jamaica"
  phone: "(718) 555-0123"
    street1: "123-10 Hillside Avenue"
    city: "Richmond Hill"
    state: "NY"
    zip: "11418"
- name: "Queens Library Forest Hills"
  phone: "(718) 555-4567"
    street1: "153 Queens BLVD"
    city: "Forest Hills"
    state: "NY"
    zip: "11375"
- name: "Norfolk Public Library"
  phone: "(211) 555-0123"
    street1: "13 Navy Lane"
    city: "Norfolk"
    state: "VA"
    zip: "28567"
- name: "Clermont Library"
  phone: "(813) 555-0123"
    street1: "100 Heat Avenue"
    city: "Clermont"
    state: "FL"
    zip: "08109"

On the generated page, I want to be able to show each state, and then a list of locations in that state. Something like:


Clermont Library - (813) 555-0123


Norfolk Public Library - (211) 555-0123


Queens Library Jamaica - (718) 555-0123
Queens Library Forest Hills - (718) 555-4567

If each location was a content/Markdown file, I could use .GroupBy and this would work perfectly. I’m trying to accomplish that same thing with a data file. Worst case scenario, I migrate the datafile to Markdown content files but there’s 100+ locations. Maintenance of this information will be much easier if it was in a single data file vs 100+ Markdown files with only a couple lines each.

I ended up figuring out a way to do this: GroupBy For Data Files in Hugo