Date Format Error With Custom Date Field

I can’t seem to find a solution to this problem, so I’m posting here in hopes of some help.

I have a custom string param in my front matter (I’m using YAML):

---
startdate: "2018-01-01"
---

In my single template I’m trying to convert this string into a date and customize the format. For simplicity I’ll just try to use the .Year here.

{{ $t := .Params.startdate | time }}
{{ $t.Year }}

This returns an error:

... at <$t.Year>: can't evaluate field Year in type *errors.errorString

I’m using Hugo 0.79.1 on Linux.

If I try to check the type of the output I get a time.Time object
{{ printf "%T" (.Params.startdate | time) }}

Using the time object returned by the page .Date works as expected. And the objects appear to be the same.
{{ printf "%T" .Date}} returns a time.Time object.

Any help or ideas would be greatly appreciated!

I suspect one or more of your content pages does not have a startdate value set in front matter. Do this:

{{- with .Params.startdate -}}
  {{- $t := time . -}}
  {{- $t.Year -}}
{{- end -}}

Or this:

{{- with .Params.startdate -}}
  {{- (time .).Year -}}
{{- end -}}
2 Likes

@jmooring You are indeed correct, and your solution works perfectly. Thank you!

Now that I think about it, it does make sense for an error to be thrown if the requested parameter is not defined on any of the pages, when requesting the value of that parameter like I was. It was just a bit disconcerting for me seeing hugo error when requesting the page that did have that parameter defined. I guess I need to be more careful of handling any parameter from page front-matter that may have a nil value on any page.

Thanks for your help!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.