Group Data byParam with date

The site I am working with has json with this structure:

{
	"discovery_date": 2021-02-16T17:57:16Z, 
    "title": "",
    "summary": "",
    "link": ""
    "published_date": ,
    "category": "",
    "source":""
}

Using something like this I can sort it by date

{{ range sort $data ".discovery_date" "desc"}}
{{.discovery_date}};
{{ end }}

But the goal I am trying to reach is to output the following:

2020
December

  • item 1
  • item 2

2021
January

  • item 3
  • item 4

Is it even possible with .Data ?

I am not sure what your .Data or $data is, but in general you do it like this (very abstract, sorry):

define yearVar as zero
define monthVar as zero
range data
  if discovery date > format as year only is different than yearVar then
    set yearVar to year
    print year
  if discovery date > format as month only is different than monthVar then
    set monthVar to month
    print month
  print current item
end

very abstract, sorry, but that’s the way to go I think.

1 Like

My data is a json file, {{ $data := $.Site.Data.articles }}.

I think I understand your abstract example, set variables for year and month and keep checking at which point in time we’re at. Sounds like something I can achieve.

Edit: May need to be sorted by discovery_date before I use it though.

Another approach:
https://discourse.gohugo.io/t/sort-two-parameters-inside-data/26636/5

2 Likes

I’m just going to leave the code here, in case anyone has the same problem to solve. Thank you to both of you! :slightly_smiling_face:

<ul>
  {{ $year := 0 }}
  {{ $month := 0 }}
  {{ $dataYear := "" }}
  {{ $dataMonth := "" }}

  {{ range sort $data ".discovery_date" "desc"}}

    {{ $dataYear = (dateFormat "2006" .discovery_date ) }}

    {{ if gt $dataYear $year }}
      {{ $year = $dataYear }}
      <h2 class="year">{{ $year }}</h2>

    {{ end }}

    {{ $dataMonth = (dateFormat "01" .discovery_date ) }}
    {{ if gt $dataMonth $month }}
      {{ $month = $dataMonth }}
      <h3 class="month">{{ dateFormat "January" .discovery_date }}</h3>
      
    {{ end }}
</ul>
2 Likes

I am pretty sure that you can leave the $dataYear and $dataMonth declaration out of the header part and define them where you create them with dateFormat because you are inside of a range. “Loops” like range and with have their own data-declaration and after range is ended they stop existing. But if it works, leave like it is. No need to change something that works, hehe.

yes you are right, variables in Hugo only exist in the scope of the range or if where they are first declared. I came into the habit of always declaring them outside of that scope in case I want to use them later for something different. It was mostly a result of constantly forgetting that I had only used them inside that one specific scope.

1 Like

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