Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update "ternary" to use "template.IsTrue" #276

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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)
}
}