Print ordinal date suffixes (1st/2nd/3rd/4th) in GoHugo

Patrick Kollitsch  | Thursday, October 28, 2021 at 9:56 pm
Photo by Mick Haupt via Unsplash
Photo by Mick Haupt via Unsplash

Golangs $date.Format is unable to add ordinal suffixes to dates (like 1st, 2nd, 3rd, 4th). Let’s not judge Golang for that. The following is how I remedy this issue:

layouts/partials/func/formatOrdinalDate.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{{- $format := .format -}}
{{- $date := .date -}}
{{- $shortend := "th" -}}
{{- if in (slice 1 21 31) $date.Day -}}
  {{- $shortend = "st" -}}
{{- else if in (slice 2 22) $date.Day -}}
  {{- $shortend = "nd" -}}
{{- else if in (slice 3 23) $date.Day -}}
  {{- $shortend = "rd" -}}
{{- end }}
{{- return $date.Format (printf $format $shortend) -}}

call to this partial:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<span title="{{- 
  with partialCached 
    "func/formatOrdinalDate" (
        dict 
            "format" "January 2%s, 2006 at 15:04 UTCMST:00" 
            "date" .Lastmod .Lastmod 
    ) 
  -}}
  {{- . -}}
{{- end -}}">

Inside of the format string you can use whatever formatting you want to display based on what Golang understands as date format string. Then add a %s at the location where you wish to have the ordinal suffix.

And that’s that.

Remotely related

Photo by Christopher Gower via Unsplash
Photo by Christopher Gower via Unsplash

CSP vs. syntax highlighting in GoHugo

If you are using the code styling functionality of GoHugo then you might have stumbled over a common issue when you are using Content Security Policies (CSP) and inline styles. Using CSPs is the proper way these days to secure your site code but it is considered (in the realm of CSPs) bad style to have your style sheets or JavaScript inlined into your page.

Read Article
Photo by Gerry Roarty on Unsplash
Photo by Gerry Roarty on Unsplash

Giscus Module for GoHugo

Giscus is a new star on the comment systems for static website generators orbit. It is inspired by the wonderful utterances and uses Github Discussions to save comments. It’s open source, easily configurable, themeable, translatable, and you can host it on your own server (it’s JavaScript based) if you like.

Read Article