diff options
author | Joe Mooring <[email protected]> | 2024-09-20 13:13:02 -0700 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2024-09-22 16:53:11 +0200 |
commit | 0ea796dad11e5d9f5b4c96a8e65f8272c9e4ccb5 (patch) | |
tree | 390654889a70867b0c6b5915acb3670d41db7626 /tpl | |
parent | 1e690c0f2311ae657fa024eae3f3b8a111e2e4c3 (diff) | |
download | hugo-0ea796dad11e5d9f5b4c96a8e65f8272c9e4ccb5.tar.gz hugo-0ea796dad11e5d9f5b4c96a8e65f8272c9e4ccb5.zip |
tpl/compare: Use any data type for compare.Conditional condition
Improves #5792
Diffstat (limited to 'tpl')
-rw-r--r-- | tpl/compare/compare.go | 4 | ||||
-rw-r--r-- | tpl/compare/compare_test.go | 34 |
2 files changed, 30 insertions, 8 deletions
diff --git a/tpl/compare/compare.go b/tpl/compare/compare.go index d6a764c6a..d32f3df95 100644 --- a/tpl/compare/compare.go +++ b/tpl/compare/compare.go @@ -231,8 +231,8 @@ func (n *Namespace) checkComparisonArgCount(min int, others ...any) bool { // Conditional can be used as a ternary operator. // // It returns v1 if cond is true, else v2. -func (n *Namespace) Conditional(cond bool, v1, v2 any) any { - if cond { +func (n *Namespace) Conditional(cond any, v1, v2 any) any { + if hreflect.IsTruthful(cond) { return v1 } return v2 diff --git a/tpl/compare/compare_test.go b/tpl/compare/compare_test.go index 6c3f43028..0ebebef4b 100644 --- a/tpl/compare/compare_test.go +++ b/tpl/compare/compare_test.go @@ -21,10 +21,9 @@ import ( "testing" "time" - "github.com/gohugoio/hugo/htesting/hqt" - qt "github.com/frankban/quicktest" "github.com/gohugoio/hugo/common/hugo" + "github.com/gohugoio/hugo/htesting/hqt" "github.com/spf13/cast" ) @@ -447,12 +446,35 @@ func TestTimeUnix(t *testing.T) { } func TestConditional(t *testing.T) { + t.Parallel() c := qt.New(t) - n := New(time.UTC, false) - a, b := "a", "b" + ns := New(time.UTC, false) - c.Assert(n.Conditional(true, a, b), qt.Equals, a) - c.Assert(n.Conditional(false, a, b), qt.Equals, b) + type args struct { + cond any + v1 any + v2 any + } + tests := []struct { + name string + args args + want any + }{ + {"a", args{cond: true, v1: "true", v2: "false"}, "true"}, + {"b", args{cond: false, v1: "true", v2: "false"}, "false"}, + {"c", args{cond: 1, v1: "true", v2: "false"}, "true"}, + {"d", args{cond: 0, v1: "true", v2: "false"}, "false"}, + {"e", args{cond: "foo", v1: "true", v2: "false"}, "true"}, + {"f", args{cond: "", v1: "true", v2: "false"}, "false"}, + {"g", args{cond: []int{6, 7}, v1: "true", v2: "false"}, "true"}, + {"h", args{cond: []int{}, v1: "true", v2: "false"}, "false"}, + {"i", args{cond: nil, v1: "true", v2: "false"}, "false"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c.Assert(ns.Conditional(tt.args.cond, tt.args.v1, tt.args.v2), qt.Equals, tt.want) + }) + } } // Issue 9462 |