HUGO

How to iterate over headless pages?

I was able to do something similar i.e. I needed to access pages programatically without rendering them.

Basically, you need to use readDir and readFile along with unmarshall which allows you to get the front matter at least in a “data” format/interface.

I, too, used readDir for this. I didn’t use readFile or unmarshal though:

You can replace

{{ range .Pages }}
...
{{ end }}

with

{{ $page := . }}
{{ range where (readDir (print "content/" .File.Dir)) ".IsDir" true }}
{{ with $page.GetPage .Name }}
...
{{ end }}
{{ end }}
1 Like

Fairly recently (around start of 2020), Hugo added support for nolist and norender , see:

and:

With that change, it’s now possible to iterate over pages that are essentially “headless”.

I’m doing it this way (the new way) with gallery items on my site. I was previously setting them to headless and using readDir , but I wanted to paginate them, and pagination only works with an actual Pages collection:

My gallery’s _index.html looks like this, to make all the gallery items get listed but for no physical pages to get generated for them:

+++
title = "Gallery"
layout = "gallery"

[_build]
render = "always"

[cascade._build]
render = "never"
list = "local"
+++
<p>Photo gallery for this site.</p>

Can see the result at: Gallery - Jaza's World Trip

Note that in the above front matter, I’m setting list = "local" , which works for my use case, but might not work for all use cases (i.e. if you want to list the “no render” items anywhere else on the site, other than on their parent page). At the moment, if you set list = "always" , then a whole lot of empty items get added to the sitemap (because “no render” items have no permalink). I’ve submitted a bug fix for this at Sitemap: exclude "no render" pages by Jaza · Pull Request #8201 · gohugoio/hugo · GitHub . Once that gets in, it should be safe to set list = "always" if you need to.