diff --git a/common/hreflect/helpers.go b/common/hreflect/helpers.go index 545371374..abb9df6b1 100644 --- a/common/hreflect/helpers.go +++ b/common/hreflect/helpers.go @@ -101,6 +101,10 @@ func IsTruthfulValue(val reflect.Value) (truth bool) { return } + if val.Kind() == reflect.Pointer && val.IsNil() { + return + } + if val.Type().Implements(zeroType) { return !val.Interface().(types.Zeroer).IsZero() } diff --git a/common/hreflect/helpers_test.go b/common/hreflect/helpers_test.go index cbcad0f22..211172d39 100644 --- a/common/hreflect/helpers_test.go +++ b/common/hreflect/helpers_test.go @@ -22,13 +22,29 @@ import ( qt "github.com/frankban/quicktest" ) +type zeroStruct struct { + zero bool +} + +func (z zeroStruct) IsZero() bool { + return z.zero +} + func TestIsTruthful(t *testing.T) { c := qt.New(t) + var nilpointerZero *zeroStruct + c.Assert(IsTruthful(true), qt.Equals, true) c.Assert(IsTruthful(false), qt.Equals, false) c.Assert(IsTruthful(time.Now()), qt.Equals, true) c.Assert(IsTruthful(time.Time{}), qt.Equals, false) + c.Assert(IsTruthful(&zeroStruct{zero: false}), qt.Equals, true) + c.Assert(IsTruthful(&zeroStruct{zero: true}), qt.Equals, false) + c.Assert(IsTruthful(zeroStruct{zero: false}), qt.Equals, true) + c.Assert(IsTruthful(zeroStruct{zero: true}), qt.Equals, false) + c.Assert(IsTruthful(nil), qt.Equals, false) + c.Assert(IsTruthful(nilpointerZero), qt.Equals, false) } func TestGetMethodByName(t *testing.T) { diff --git a/markup/tableofcontents/tableofcontents_integration_test.go b/markup/tableofcontents/tableofcontents_integration_test.go index e6ae03ce2..b47cbd245 100644 --- a/markup/tableofcontents/tableofcontents_integration_test.go +++ b/markup/tableofcontents/tableofcontents_integration_test.go @@ -121,3 +121,16 @@ CONTENT b, _ = hugolib.TestE(t, files) b.AssertLogMatches(`error calling ToHTML: startLevel: unable to cast "x" of type string`) } + +func TestHeadingsNilpointerIssue11843(t *testing.T) { + t.Parallel() + files := ` +-- hugo.toml -- +-- layouts/home.html -- +{{ $h := index .Fragments.HeadingsMap "bad_id" }} +{{ if not $h }}OK{{ end }} +` + b := hugolib.Test(t, files) + + b.AssertFileContent("public/index.html", "OK") +}