The Manual Way
The simplest way is to record a lastmod
date and time within your post’s header - like the example below:
---
title: My Example Post
date: 1990-01-01T00:00:00+00:00
lastmod: 1995-04-04T00:00:00+00:00
url: /example-post/
---
We can then use this information in our theme and layouts to display the information. In our code, we don’t show the last updated date if it’s the same as the created date (there’s no point?)
<!-- Created Date -->
{{- $pubdate := .PublishDate.Format "02.01.2006" }}
Created:
<time datetime="{{ .PublishDate }}" title="{{ .PublishDate }}">
{{ $pubdate }}
</time>
<!-- Last Updated Date -->
{{- if .Lastmod }}
{{- $lastmod := .Lastmod.Format "02.01.2006" }}
{{- if ne $lastmod $pubdate }}
<div class="post-info-last-mod">
(Updated:
<time datetime="{{ .Lastmod }}" title="{{ .Lastmod }}">
{{ $lastmod }}
</time>)
</div>
{{- end }}
{{- end }}
Output:
Created: 01.01.1990
(Updated: 04.04.1995)
The Git way
Hugo can actually hook into your git (the version control system) information and pull the last edited times from there. To enable it, just change this setting in your config.
config.toml
enableGitInfo = true
This will now automatically pull in the last updated times and fill in lastmod
for you - Neat!
Or
$ hugo server --disableFastRender --enableGitInfo
It will, however, overwrite any of your manually created lastmod
dates. You can choose to change this behaviour to favour your lastmod
times but if they don’t exist then use git. To do this, we need to add one final part to our config changing the front matter dates:
[frontmatter]
date = ["date", "publishDate", "lastmod"]
lastmod = [':git', 'lastmod', 'date', 'publishDate']
publishDate = ["publishDate", "date"]
expiryDate = ["expiryDate"]
Reference
- https://makewithhugo.com/add-a-last-edited-date/
- https://gohugo.io/variables/git/
- https://gohugo.io/getting-started/configuration/
- https://www.andrewjstevens.com/posts/2021/03/last-modified-date-with-hugo/