Sort folders by newest post in folders

Within a list page at https://domain.com/university I list all the modules I participate in.
The basic file hierarchy looks something like that:

content/
├── about.md
└── university
    ├── 2101-mathematik-1
    │   ├── 07-10-2021.md
    │   └── _index.md
    ├── 2102-einfuehrung-in-die-informatik-1
    │   └── _index.md
    ├── 2103-digital-business
    │   ├── 08-10-2021.md
    │   └── _index.md
    ├── 2104-mathematik-3-stochastik-statistik
    │   └── _index.md
    └── _index.md

I want to sort the subfolders under university/ by the newest post appearing in them. If a new post is added to a folder currently on the bottom of the page, it should move to the top.

Currently I use this code snipped within layouts/section/university.html:

{{ define "main" }}
  <h1 class="page-title">{{ .Title }}</h1>
  
    {{ range (site.GetPage "university").Sections }} <!-- .ByDate.Reverse -->
      <ul>
        {{ range .Pages}}
          <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
        {{ end }}
      </ul>
    {{ end }}
{{ end }}

This currently just sorts the folders by name.

I cannot just change

{{ range (site.GetPage "university").Sections }}

to

{{ range (site.GetPage "university").Sections.ByDate.Reverse }}

as this refers back to the folder, not the posts within them.

If someone got any idea, I would be glad to hear it!

You can have a look how it looks in action on: https://lucaschulz.xyz/university

It sounds like you want sort the sections by the date of the most recent post within each section. Is that correct?

Hi jmooring,

thanks for your answer! Yes, that’s the plan.

edit: to be completely clear: The sections should be sorted by the date, posts in them were created.

{{/*
Build slice of maps, one map for each section. Each map contains three
items:
- dateOfNewestPage: The date of the newest page within the section
- page: The section's page object (to access section .Title, etc.)
- pages: A collection of the pages within the section
*/}}

{{ $sections := slice }}
{{ range (site.GetPage "university").Sections }}
  {{ $dateOfNewestPage := (index .Pages.ByDate.Reverse 0).Date }}
  {{ $sections = $sections | append (dict "dateOfNewestPage" $dateOfNewestPage "page" . "pages" .Pages) }}
{{ end }}

{{ range sort $sections "dateOfNewestPage" "desc" }}
  <h2>{{ .page.Title }}</h2> {{/* .page is the current section page */}}
  <ul>
    {{ range .pages.ByDate.Reverse }} {{/* .pages is the collection of pages within the current section */}}
      <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
    {{ end }}
  </ul>
{{ end }}
1 Like

Wow. Thank you so much for even commenting on what your example code does. It works incredible well. I will push a commit in a few minutes! Have a nice day, @jmooring , you helped me out!

1 Like

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