Rendering a comma-separated list of items in a Hugo template with a dot after the last

Here’s a Hugo template snippet for rendering a list of items separated by a comma and space after all but the last item, and then a dot or full stop.

For example, if you have a tags taxonomy and some tags in a post’s front-matter like this:

 - Foo
 - Bar
 - Baz

You can render a comma-separated list of those tags in a template like this:

{{ with (.GetTerms "tags") }}
  {{ range $i, $t := . }}{{ if $i }},&nbsp;{{ end }}<a href="{{ $t.Permalink }}">{{ $t.LinkTitle }}</a>{{ end }}.
{{ end }}

The $i variable is the numeric range index and the $t variable is the tag object per tag. This uses the false evaluation of the first index 0 to add a comma and space “,&nbsp;” after all but the first item in the range.

Note that you do need to be careful with the line breaks in the template, otherwise you’ll end up with unwanted white-space around the commas and full-stop at the end.

This will produce HTML output like this in the rendered site:

  <a href="/tags/foo">Foo</a>, <a href="/tags/bar">Bar</a>, <a href="/tags/baz">Baz</a>.

I used this approach to render natural-looking comma-separated text lists of the various product taxonomies on our wall art prints shop, which is powered by Hugo for the static parts of the site.

Tech mentioned