Why won't time.Format accept input read from Json data?

Edit: as explained in my subsequent post, there’s nothing wrong with passing variables to time.Format, provided that variable has a string value.

I’m struggling to get time.Format to accept data read from a json file.

The original data looks like

{ "startDate": "2023-01-28T15:00" }

Which I’ve put in a variable $json_data.startDate

What I’m essentially trying to do is

{{ time.Format "Monday, Jan 2, 2006" "2023-01-28"  }}

Except passing “2023-01-28” as a variable. The snag I’ve hit is

{{ time.Format "Monday, Jan 2, 2006" (substr $json_map.startDate 0 10) }}

causes running hugo to barf:

$ hugo
Start building sites … 
hugo v0.108.0+extended linux/amd64 BuildDate=unknown
ERROR 2023/01/12 08:33:19 render of "page" failed: "/home/roblaing/webapps/joeblog/themes/joetheme/layouts/_default/single.html:8:7": execute of template failed: template: _default/single.html:8:7: executing "main" at <time.Format>: error calling Format: unable to parse date: 
Error: Error building site: failed to render pages: render of "page" failed: "/home/roblaing/webapps/joeblog/themes/joetheme/layouts/_default/single.html:8:7": execute of template failed: template: _default/single.html:8:7: executing "main" at <time.Format>: error calling Format: unable to parse date: 
Total in 40 ms

There’s something clearly wrong with the type of the substring. But

{{ eq (substr $json_map.startDate 0 10) "2023-01-28" }}

is true, so I’m at a loss at how to transform the input.

I found a similar question from a while back at Date in Template from Data (json) but couldn’t figure out the solution from the replies.

How did you do this? Seeing more of your code would be helpful.

1 Like

I’ve read it from a json file in the data directory using

{{ $json_map := (index (index .Site.Data .Page.Section) (path.Base .RelPermalink)) }}

Maybe your data structure isn’t what you think it is.

This works fine:

data/foo.json

{
  "startDate": "2023-01-28T15:00"
}

template

{{ $json_map := site.Data.foo }}
{{ time.Format "Monday, Jan 2, 2006" (substr $json_map.startDate 0 10) }}

output

Saturday, Jan 28, 2023
1 Like

It turns out there’s nothing wrong with Hugo’s time.Format, just that I forgot to guard against attempting to read json files which don’t have the “startDate” key.

Adding this guard fixed it:

{{ if isset $json_map "startDate" }}
{{ time.Format "Monday, Jan 2, 2006" (substr $json_map.startDate 0 10) }}
{{ end }}

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