Skip to content

Commit

Permalink
Adding new conv.Default function
Browse files Browse the repository at this point in the history
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
  • Loading branch information
hairyhenderson committed Apr 20, 2018
1 parent c9aa02c commit 628a316
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
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))
}
})
}
}

0 comments on commit 628a316

Please sign in to comment.