I want to display a list of events, coming from an JSON API, grouped by their months. How can I achieve this, without changing the returning JSON object itself?
The JSON object format is something like
{
…
“time” : “2006-01-02T15:04:05Z07:0000Z”,
…
}
Some possible solutions could be:
- The RESTful API could take the month as parameter and just return specific events
- Creating a map in the template. (Is this possible or does exists a function for grouping JSON objects?)
- Some ugly stuff during ranging all objects and try to check if the previous month is different and create group header by change.
Or does a other way exists to use the section build-in functionality of Hugo in combination with an JSON array?
I played around to achieve my desired result, but it does not work really well. Currently I’m playing around with $.Scratch …
to filter my objects from the JSON.
What I want to achieve is something like:
January
February
April
Does anybody had a similar problem to solve?
I solved the problem by myself and would like to share my solution. If somebody has suggestions how I can is solve this use case in an easier way, I would be happy to here it. Maybe in the future we have a better way to generate a view based on JSON only.
Solution:
{{ $data := (index .Site.Data .Params.data) }}
{{ $.Scratch.Set "isMonthHeaderCreated" false }}
{{ range $monthIndex := (seq 1 12) }}
{{ range $value := $data }}
{{ $currentMonth := (dateFormat "1" $value.time)}}
{{ $isCurrentMonth := (eq $monthIndex (int $currentMonth)) }}
{{ $isSection := (and $isCurrentMonth (not ($.Scratch.Get "isMonthHeaderCreated"))) }}
{{ if $isSection }}
{{ $.Scratch.Set "isMonthHeaderCreated" true }}
{{ dateFormat "January" $value.time }}</strong>
<ul>
{{ end }}
{{ if $isCurrentMonth }}
<li>{{ $value.title }}</li>
{{ end }}
{{ if (and (not $isCurrentMonth) ($.Scratch.Get "isMonthHeaderCreated")) }}
</ul>
{{ $.Scratch.Set "isMonthHeaderCreated" false }}
{{ end }}
{{ end }}
{{ end }}
@Pyth0ff Can you do me a favor and add “[SOLVED]” to the beginning of this heading just for helping other users of the forum search in the future. Cheers.