tpl/time: Handle nil values in time.AsTime

Closes #8865
This commit is contained in:
Bjørn Erik Pedersen 2021-08-09 18:44:35 +02:00
parent 9bba9a3a98
commit 3e11072892
No known key found for this signature in database
GPG key ID: 330E6E2BD4859D8F
2 changed files with 9 additions and 1 deletions

View file

@ -19,6 +19,8 @@ import (
"time" "time"
_time "time" _time "time"
"github.com/gohugoio/hugo/common/hreflect"
"github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/htime"
"github.com/gohugoio/locales" "github.com/gohugoio/locales"
@ -43,6 +45,9 @@ type Namespace struct {
// AsTime converts the textual representation of the datetime string into // AsTime converts the textual representation of the datetime string into
// a time.Time interface. // a time.Time interface.
func (ns *Namespace) AsTime(v interface{}, args ...interface{}) (interface{}, error) { func (ns *Namespace) AsTime(v interface{}, args ...interface{}) (interface{}, error) {
if !hreflect.IsTruthful(v) {
return time.Time{}, nil
}
loc := ns.location loc := ns.location
if len(args) > 0 { if len(args) > 0 {
locStr, err := cast.ToStringE(args[0]) locStr, err := cast.ToStringE(args[0])

View file

@ -29,7 +29,7 @@ func TestTimeLocation(t *testing.T) {
for i, test := range []struct { for i, test := range []struct {
name string name string
value string value interface{}
location interface{} location interface{}
expect interface{} expect interface{}
}{ }{
@ -39,6 +39,9 @@ func TestTimeLocation(t *testing.T) {
{"New York EST", "2020-01-20", "America/New_York", "2020-01-20 00:00:00 -0500 EST"}, {"New York EST", "2020-01-20", "America/New_York", "2020-01-20 00:00:00 -0500 EST"},
{"Empty location, time", "2020-10-20 20:33:59", "", "2020-10-20 20:33:59 +0000 UTC"}, {"Empty location, time", "2020-10-20 20:33:59", "", "2020-10-20 20:33:59 +0000 UTC"},
{"New York, time", "2020-10-20 20:33:59", "America/New_York", "2020-10-20 20:33:59 -0400 EDT"}, {"New York, time", "2020-10-20 20:33:59", "America/New_York", "2020-10-20 20:33:59 -0400 EDT"},
{"Nil value", nil, "", "0001-01-01 00:00:00 +0000"},
{"Empty value", "", "", "0001-01-01 00:00:00 +0000"},
// The following have an explicit offset specified. In this case, it overrides timezone // The following have an explicit offset specified. In this case, it overrides timezone
{"Offset minus 0700, empty location", "2020-09-23T20:33:44-0700", "", "2020-09-23 20:33:44 -0700 -0700"}, {"Offset minus 0700, empty location", "2020-09-23T20:33:44-0700", "", "2020-09-23 20:33:44 -0700 -0700"},
{"Offset plus 0200, empty location", "2020-09-23T20:33:44+0200", "", "2020-09-23 20:33:44 +0200 +0200"}, {"Offset plus 0200, empty location", "2020-09-23T20:33:44+0200", "", "2020-09-23 20:33:44 +0200 +0200"},