diff --git a/docs/content/en/functions/truth.md b/docs/content/en/functions/truth.md index 88f7e71d1bb..27c636b9dee 100644 --- a/docs/content/en/functions/truth.md +++ b/docs/content/en/functions/truth.md @@ -24,19 +24,19 @@ It follows the same rules as [`bool`](/functions/bool), but with increased flexi ``` {{ truth "true" }} → true -{{ truth "false" }} → false +{{ truth "false" }} → true {{ truth "TRUE" }} → true -{{ truth "FALSE" }} → false +{{ truth "FALSE" }} → true {{ truth "t" }} → true -{{ truth "f" }} → false +{{ truth "f" }} → true {{ truth "T" }} → true -{{ truth "F" }} → false +{{ truth "F" }} → true {{ truth "1" }} → true -{{ truth "0" }} → false +{{ truth "0" }} → true {{ truth 1 }} → true {{ truth 0 }} → false diff --git a/tpl/cast/cast.go b/tpl/cast/cast.go index 133ab3a477c..d0e291dbff5 100644 --- a/tpl/cast/cast.go +++ b/tpl/cast/cast.go @@ -17,6 +17,7 @@ package cast import ( "html/template" + "github.com/gohugoio/hugo/common/hreflect" _cast "github.com/spf13/cast" ) @@ -49,23 +50,18 @@ func (ns *Namespace) ToFloat(v any) (float64, error) { // ToBool converts v to a boolean. func (ns *Namespace) ToBool(v any) (bool, error) { v = convertTemplateToString(v) - return _cast.ToBoolE(v) + result, err := _cast.ToBoolE(v) + if err != nil { + return false, nil + } + return result, nil } // ToTruth yields the same behavior as ToBool when possible. // If the cast is unsuccessful, ToTruth converts v to a boolean using the JavaScript [definition of truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). // Accordingly, it never yields an error, but maintains the signature of other cast methods for consistency. func (ns *Namespace) ToTruth(v any) (bool, error) { - result, err := ns.ToBool(v) - if err != nil { - switch v { - case "", "nil", "null", "undefined", "NaN": - return false, nil - default: - return true, nil - } - } - return result, nil + return hreflect.IsTruthful(v), nil } func convertTemplateToString(v any) any { diff --git a/tpl/cast/cast_test.go b/tpl/cast/cast_test.go index 4c027b956c4..ec45b2291a1 100644 --- a/tpl/cast/cast_test.go +++ b/tpl/cast/cast_test.go @@ -147,7 +147,6 @@ func TestToBool(t *testing.T) { // error cases {"cheese", nil, false}, {"", nil, false}, - {1.67, nil, false}, } { errMsg := qt.Commentf("[%d] %v", i, test.v) @@ -173,15 +172,15 @@ func TestToTruth(t *testing.T) { expect any }{ {"true", true}, - {"false", false}, + {"false", true}, {"TRUE", true}, - {"FALSE", false}, + {"FALSE", true}, {"t", true}, - {"f", false}, + {"f", true}, {"T", true}, - {"F", false}, + {"F", true}, {"1", true}, - {"0", false}, + {"0", true}, {1, true}, {0, false}, {"cheese", true}, @@ -194,9 +193,9 @@ func TestToTruth(t *testing.T) { {template.JSStr("6"), true}, {t, true}, {nil, false}, - {"null", false}, - {"undefined", false}, - {"NaN", false}, + {"null", true}, + {"undefined", true}, + {"NaN", true}, } { errMsg := qt.Commentf("[%d] %v", i, test.v)