Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"math/rand"
"reflect"
"strings"
"text/template"
"time"
)

Expand Down Expand Up @@ -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 {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my own library, I'd implemented this with a panic for !ok (which I'm happy to adjust this to), but I wasn't sure if panic was appropriate here. 😅

return vt
}

Expand Down
20 changes: 20 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}