From 32d2c8859a05e5f53e5c18661f71156b48bd08f2 Mon Sep 17 00:00:00 2001 From: Tianon Gravi Date: Mon, 21 Dec 2020 17:18:12 -0800 Subject: [PATCH] Update "ternary" to use "template.IsTrue" This adjusts `ternary` to use the same `template.IsTrue` that controls the semantics of the built-in `if` (and friends). For further context, `template.IsTrue` has been officially exported since Go 1.6 (https://github.com/golang/go/commit/a326c3e1ad3713c3e1c3373a45c6907e10fb1579). --- defaults.go | 5 +++-- defaults_test.go | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/defaults.go b/defaults.go index b9f97966..5d250565 100644 --- a/defaults.go +++ b/defaults.go @@ -6,6 +6,7 @@ import ( "math/rand" "reflect" "strings" + "text/template" "time" ) @@ -154,8 +155,8 @@ func mustToRawJson(v interface{}) (string, error) { } // ternary returns the first value if the last value is true, otherwise returns the second value. -func ternary(vt interface{}, vf interface{}, v bool) interface{} { - if v { +func ternary(vt interface{}, vf interface{}, v interface{}) interface{} { + if truth, ok := template.IsTrue(v); ok && truth { return vt } diff --git a/defaults_test.go b/defaults_test.go index a35ebf62..8bd6292f 100644 --- a/defaults_test.go +++ b/defaults_test.go @@ -193,4 +193,24 @@ func TestTernary(t *testing.T) { if err := runt(tpl, "bar"); err != nil { t.Error(err) } + + tpl = `{{ternary "foo" "bar" "baz"}}` + if err := runt(tpl, "foo"); err != nil { + t.Error(err) + } + + tpl = `{{"baz" | ternary "foo" "bar"}}` + if err := runt(tpl, "foo"); err != nil { + t.Error(err) + } + + tpl = `{{ternary "foo" "bar" ""}}` + if err := runt(tpl, "bar"); err != nil { + t.Error(err) + } + + tpl = `{{"" | ternary "foo" "bar"}}` + if err := runt(tpl, "bar"); err != nil { + t.Error(err) + } }