#Hugo

How To Render Grouped Articles

Saturday, February 29, 2020

To render a group of articles we need a function to group them by a key. Hugo provides a few APIs to do so:

API example
group {{ $new := .Site.RegularPages \| first 10 \| group "New" }}
.Pages.GroupBy {{ range .Pages.GroupBy "Section" }}
.Pages.GroupByDate {{ range .Pages.GroupByDate "2006-01" }}
.Pages.GroupByPublishDate {{ range .Pages.GroupByPublishDate "2006-01" }}
.Pages.GroupByParam {{ range .Pages.GroupByParam "param_key" }}
.Pages.GroupByParamDate {{ range .Pages.GroupByParamDate "param_key" "2006-01" }}

For the articles list in Today I Learned, I used .Pages.GroupByParam to group the articles by the param category I defined in every post and then sort them by date in an desending order so the recent articles of every category are rendered.

{{ range ((.Site.GetPage "section" "/today-i-learned").Pages.GroupByParam "category") }}
    <h2>{{ .Key }}</h2>
    {{ range .Pages.ByDate.Reverse }}
    <a href="{{ .URL }}" class="article-teaser">
        <h6>{{ .Title }}</h6>
    </a>
    {{ end }}
{{ end }}