How to Add a Last Modified Date in Hugo Articles
How can we add a Last Modified, Last Updated, or Last Edited date to our Hugo posts?
Suppose we want to conditionally render a Last Modified date in the single.html template for our posts.
Published {{ .Date.UTC.Format "Jan 2, 2006" }}
Last Modified {{ .Lastmod.UTC.Format "Jan 2, 2006" }}
Here, we use Hugo’s date and lastmod fields.
If we have times in multiple timezones, we should normalize them by converting them all to UTC or all to our local timezone using
UTCandLocal, respectively.
There are two ways we can go about approaching this problem.
1. Automatically add lastmod field using Git metadata
We can automatically add the lastmod field to each article based on Git information.
Update enableGitInfo in config.yaml
First, we need to set enableGitInfo to true in our config.yaml.
enableGitInfo: true
The lastmod field will default to the most recent commit date for that file in Git.
Update frontmatter in config.yaml
If enableGitInfo is true, it will override any lastmod dates in our front matter.
We should at least allow ourselves to manually override this value in the front matter.
Let’s update our config.yaml.
frontmatter:
lastmod:
- lastmod
- :git
- date
- publishDate
This approach isn’t recommended, since changes to a Git file may not always correlate to changes in the article content. It could simply be a minor style change or other changes that aren’t relevant to the content.
2. Manually add lastmod to front matter
The second approach we can take is to manually add lastmod fields to front matter whenever we update an article.
We want the Last Modified date to show only if we explicitly set it in the front matter.
Add lastmod to front matter
Let’s add the lastmod field to our article front matter.
date: "2022-01-10"
lastmod: "2022-01-15"
Update frontmatter in config.yaml
If enableGitInfo is true, lastmod will be set to the most recent commit date for that file and override any lastmod dates.
If not, it will be set to the first non-null value in the article front matter dates: ["lastmod", "date", "publishDate"]
However, in this approach, we don’t want any defaults for lastmod.
We can prevent lastmod from defaulting to any other date by exclusively setting lastmod to be the value specified in our front matter, otherwise it’ll be null.
frontmatter:
lastmod:
- lastmod
Fix single.html conditional
Let’s fix our conditional to check that lastmod exists and is greater than date (i.e. the last modified date must be after the publish date).
{{ $date := .Date.UTC.Format "Jan 2, 2006" }}
{{ $lastmod := .Lastmod.UTC.Format "Jan 2, 2006" }}
Published {{ $date }}
{{ if and (ne $lastmod $date) (gt .Lastmod .Date) }}
<br/>Updated {{ $lastmod }}
{{ end }}
The first conditional checks that the formatted date strings aren’t equal while the second conditional checks the timestamp.