Formatting a slice of dates (iterate/transform or map slices)

Hi,

I’ve got a slice of dates:

dates = ["2019-01-01", "2019-03-02", "2019-06-02"]

I want to produce:

<h6>Dates: January 2019, March 2019, June 2019</h6>

I’ve been trying to work with range, slice, dateFormat, and delimit and running into headaches.

I was hoping something like:

{{ with .dates }}
  {{ $renderedDates := slice({{ range . }}{{ dateFormat "January 2006" . }}{{ end }} }}
  <h6>{{ delimit $renderedDates ", " }}<h6>
{{ end }}

What is the go/Hugo right way to do this?

What you are looking for is the apply function:

{{ delimit (apply $dates "dateFormat" "January 2006" ".") ", " }}

Or long ways:

{{ $newdates := slice }}
{{ range $dates }}
  {{ $newdates = $newdates | append ( dateFormat "January 2006" .) }}
{{ end }}

{{ delimit $newdates ", "}}
3 Likes

Thank you! I thought I had rtfm’ed thoroughly but completely missed apply.

Works like a charm!