Published on

How to show Recent Blog Posts on Homepage in Hugo

It's pretty straightforward. You'll be making these changes in the themes directory. In my case, I'm using hugo-bearblog so the below files are under themes/hugo-bearblog/layouts directory.

Create a partial (layouts/partials/recent-posts.html) file for recent blog posts.

<h2>Recent Posts</h2>
<ul>
  {{ range first 5 (where .Site.RegularPages "Type" "blog") }}
    <li>
      <a href="{{ .Permalink }}">{{ .Title }}</a>
      <span class="date">{{ .Date.Format "January 1, 2024" }}</span>
    </li>
  {{ end }}
</ul>

The range function in Hugo helps us to iterate over various types. In our case, it's used to get the first 5 blog posts.

Assuming you've your blog posts under blog directory inside content. In case, if you have it under a different category like posts replace it with something like range first 5 (where .Site.RegularPages "Type" "posts")

And include this partial in your index.html page.

{{ define "main" }}
  {{ .Content }}
  {{ partial "recent-posts.html" . }}
{{ end }}

Happy customizing homepage!