tpl: updates cast.ToTruth to conform to hreflect.IsTruthful

Concession from review, where cast.ToTruth should behave exactly like hreflect.IsTruthful.
Additionally, cast.ToBool always returns a bool with nil error.
This commit is contained in:
ksaleem 2023-10-17 23:38:01 -04:00
parent 5a72de2600
commit 28434238db
3 changed files with 22 additions and 30 deletions

View file

@ -20,23 +20,21 @@ aliases: []
Useful for turning different types into booleans based on their [truthy-ness](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
It follows the same rules as [`bool`](/functions/bool), but with increased flexibility.
```
{{ 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

View file

@ -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 {

View file

@ -144,10 +144,8 @@ func TestToBool(t *testing.T) {
{false, false, nil},
{nil, false, nil},
// error cases
{"cheese", nil, false},
{"", nil, false},
{1.67, nil, false},
{"cheese", false, nil},
{"", false, nil},
} {
errMsg := qt.Commentf("[%d] %v", i, test.v)
@ -173,15 +171,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 +192,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)