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

Adding new conv.Default function #298

Merged
merged 1 commit into from
Apr 20, 2018
Merged
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
18 changes: 18 additions & 0 deletions docs/content/functions/conv.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,24 @@ $ FOO=true gomplate < input.tmpl
foo
```

## `conv.Default`

**Alias:** `default`

Provides a default value given an empty input. Empty inputs are `0` for numeric
types, `""` for strings, `false` for booleans, empty arrays/maps, and `nil`.

Note that this will not provide a default for the case where the input is undefined
(i.e. referencing things like `.foo` where there is no `foo` field of `.`), but
[`conv.Has`](#conv-has) can be used for that.

#### Example

```console
$ gomplate -i '{{ "" | default "foo" }} {{ "bar" | default "baz" }}'
foo bar
```

## `conv.Slice`

**Alias:** `slice`
Expand Down
10 changes: 10 additions & 0 deletions funcs/conv.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package funcs
import (
"net/url"
"sync"
"text/template"

"github.com/hairyhenderson/gomplate/conv"
)
Expand All @@ -27,6 +28,7 @@ func AddConvFuncs(f map[string]interface{}) {
f["has"] = ConvNS().Has
f["slice"] = ConvNS().Slice
f["join"] = ConvNS().Join
f["default"] = ConvNS().Default
}

// ConvFuncs -
Expand Down Expand Up @@ -111,3 +113,11 @@ func (f *ConvFuncs) ToFloat64s(in ...interface{}) []float64 {
func (f *ConvFuncs) ToString(in interface{}) string {
return conv.ToString(in)
}

// Default -
func (f *ConvFuncs) Default(def, in interface{}) interface{} {
if truth, ok := template.IsTrue(in); truth && ok {
return in
}
return def
}
39 changes: 39 additions & 0 deletions funcs/conv_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package funcs

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestDefault(t *testing.T) {
s := struct{}{}
c := ConvNS()
def := "DEFAULT"
data := []struct {
val interface{}
empty bool
}{
{0, true},
{1, false},
{nil, true},
{"", true},
{"foo", false},
{[]string{}, true},
{[]string{"foo"}, false},
{[]string{""}, false},
{c, false},
{s, false},
}

for _, d := range data {
t.Run(fmt.Sprintf("%T/%#v empty==%v", d.val, d.val, d.empty), func(t *testing.T) {
if d.empty {
assert.Equal(t, def, c.Default(def, d.val))
} else {
assert.Equal(t, d.val, c.Default(def, d.val))
}
})
}
}