Display 3 most recent blog posts in Hugo (but not other pages)
Asked Answered
L

2

7

I have a site with a bunch of static pages, plus a blog, in Hugo.

On the front page, I'd like to create short links to the three most recent blog posts (but not to any possibly recently modified static page). The blog posts are all in directory blog/.

I'm failing to figure out the syntax for this. So far, I have:

{{- range (.Paginate ( first 3 .Pages.ByDate )).Pages }}
    <li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
{{- end}}

but I need to also filter by directory blog/. This is in my layouts/index.html template.

Luba answered 11/12, 2019 at 1:22 Comment(0)
C
7

I'm using Hugo 0.74.3 and this is my solution:

{{ range ( where .Site.RegularPages "Type" "posts" | first 3 ) }}
  <li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
{{end}}

Note that blog posts with draft: true in their frontmatter are not included.


I started by just iterating over .Site.RegularPages without the where to figure it out

{{ range .Site.RegularPages }}
  <h2>{{ . }}</h2>
{{end}}
Cubby answered 23/9, 2020 at 4:47 Comment(0)
T
1

Hugo is tricky to get the filtering working, but this may work for you

{{ range ( first 3 ( where .Site.Pages "Type" "blog" ).ByDate ) }}
  <li><a href="{{ .Permalink }}">{{ .Title }}</a></li>
{{ end }}
Tameika answered 25/1, 2020 at 13:10 Comment(1)
Or you can .ByDate after .Pages, to remove the bracket to increase the readability e.g. {{ range first 3 ( where .Site.Pages.ByDate "Type" "blog" ) }}Astonish

© 2022 - 2024 — McMap. All rights reserved.