I like to display “published date” and “last modified date” info for my posts. Date info comes from the date
parameter and last modified info comes from the lastmod
parameter, both defined in the front-matter.
date: "2020-08-22"
lastmod: "2020-08-22"
Get Date-Info Partial
To get date-info I’ve created a simple partial template. Which basically, checks if the “lastmod” and publish dates are the same then renders the dates. To compare two dates, we should format them using the same date format. “02.01.2006” is equal to “dd.mm.yyyy” in the Go language.
{{ $date := .Date.Format "02.01.2006" }}
{{ $lastmod := .Lastmod.Format "02.01.2006" }}
<span class="date-info italic">published on {{ $date }}</span>
{{ if ne $lastmod $date }}
<span class="date-info italic"> <br> edited on {{ .Lastmod.Format "02.01.2006" }}</span>
{{ end }}
Get LastMod Using Git
There is a very cool feature in Hugo, that can get the “lastmod” info from git. You need to enable it in the config file: config.toml
.
enableGitInfo = true
Still, if lastmod
parameter exists in front-matter, Hugo will use the date from the from-matter, not from git. So, you can freely enable the feature and use the parameter whenever you want to manually enter another date.
I realized that Hugo still using the lastmod info that is coming from git even if we set the lastmod
parameter in the front-matter. The good thing is we can change this behavior by configuring front matter.
[frontmatter]
date = ["date", "publishDate", "lastmod"]
lastmod = ["lastmod", ":git", "date", "publishDate"]
publishDate = ["publishDate", "date"]
expiryDate = ["expiryDate"]
By default, ":git"
comes before "lastmod"
. To override it, we need to add these lines to the config file.