I am trying to retrieve the latest 10 posts from a specific path in my Hugo project. The posts are Markdown files located in /content/laws/union/enviornment/ and I want to display them in descending order of their Date. Here’s what I’ve tried so far:
However, this doesn’t seem to work, and I’m not sure why. I’ve also tried using .Site.Pages with the where filter, but I’m not getting the expected results.
Can anyone help me with the correct way to pull the latest 10 posts from that specific directory, and possibly point me to the right documentation or examples?
With the exception of top level directories, a directory must have an _index.md file to be a section.
With that content structure you can do:
{{ with site.GetPage "/laws/union/environment" }}
{{ with .Pages.ByDate.Reverse | first 10 }}
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
{{ end }}
The above codes defensively against (a) a non-existent section and (b) zero pages in the section. It silently renders nothing if either is true.
It worked, thank you! I had initially included an empty index.md file, assuming that leaf bundles require an index.md and branch bundles require _index.md, as suggested in the Hugo documentation.
By the way, how can I list all the sections or branch bundles names under ‘union’ and provide a permalink to a list view for them?
Then range over the sections within the union section:
{{ with site.GetPage "/laws/union" }}
{{ with .Sections }}
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
{{ end }}
</ul>
{{ end }}
{{ end }}
Or, if you want this list to be published to https://example.org/laws/union…
content/laws/union/_index.md
---
title: Union laws
layout: union
---
layouts/laws/union.html
{{ define "main" }}
<h1>{{ .Title }}</h1>
{{ .Content }}
{{ range .Sections }}
<h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
{{ end }}
{{ end }}
Big thanks for the solid help! Your advice cut through the confusion like a hot knife through butter. Appreciate the time you took to break things down. Hugo’s a beast of a tool, and it’s folks like you that make mastering it a hell of a lot easier. !