Open Source

How to Add Last Modified Date to Articles with Hugo?

Reading Time : 2 min

The infrastructure of my site is Hugo, and from time to time I like to improve myself and update the theme structure with the simple but powerful variables that Hugo provides.

I can fetch “Published Date” and “Last Modified Date” for articles with Hugo. For this, the date information comes from the date and the last updated date lastmod parameters. Both can be defined in front-matter.

You can enter your front-matter dates manually and easily make it default with archetypes. Simply add something like this to the front-matter:

date: "2023-02-28"
lastmod: "2023-03-01"

Then in your layout template, for example single.html to access this data:

{{ $date := .Date.Format "02.01.2006" }}
{{ $lastmod := .Lastmod.Format "02.01.2006" }}

Published: {{ $date }}
Last Updated: {{ $lastmod }}

Hugo’s predefined frontmatter variable LastMod provides important details. But there is an even better feature that Hugo offers for lastmod. Hugo’s GIT integration is able to get the LastMod value from the file’s GIT history. First enable git info in config.toml.

enableGitInfo: true

As soon as you activate the above, Hugo will override all lastmod dates entered in the front-matter. This means by default “:git” comes before lastmod.

We need to add the following lines to the config file to change and overwrite this.

date = ["date", "publishDate", "lastmod"]
lastmod = ["lastmod", ":git", "date", "publishDate"]

Thus, if Hugo sees the lastmod parameter in the front-matter, will use it, but if there is no value related to lastmod, Hugo will consider the last git commit as the last modified date.