tpl: Improve template funcs GoDoc

This commit is contained in:
Bjørn Erik Pedersen
2022-12-21 13:11:08 +01:00
parent aa2c724195
commit cd1ed563a8
17 changed files with 170 additions and 163 deletions

View File

@@ -40,25 +40,25 @@ type Namespace struct {
caseInsensitive bool
}
// Default checks whether a given value is set and returns a default value if it
// Default checks whether a givenv is set and returns the default value defaultv if it
// is not. "Set" in this context means non-zero for numeric types and times;
// non-zero length for strings, arrays, slices, and maps;
// any boolean or struct value; or non-nil for any other types.
func (*Namespace) Default(dflt any, given ...any) (any, error) {
func (*Namespace) Default(defaultv any, givenv ...any) (any, error) {
// given is variadic because the following construct will not pass a piped
// argument when the key is missing: {{ index . "key" | default "foo" }}
// The Go template will complain that we got 1 argument when we expected 2.
if len(given) == 0 {
return dflt, nil
if len(givenv) == 0 {
return defaultv, nil
}
if len(given) != 1 {
return nil, fmt.Errorf("wrong number of args for default: want 2 got %d", len(given)+1)
if len(givenv) != 1 {
return nil, fmt.Errorf("wrong number of args for default: want 2 got %d", len(givenv)+1)
}
g := reflect.ValueOf(given[0])
g := reflect.ValueOf(givenv[0])
if !g.IsValid() {
return dflt, nil
return defaultv, nil
}
set := false
@@ -77,7 +77,7 @@ func (*Namespace) Default(dflt any, given ...any) (any, error) {
case reflect.Complex64, reflect.Complex128:
set = g.Complex() != 0
case reflect.Struct:
switch actual := given[0].(type) {
switch actual := givenv[0].(type) {
case time.Time:
set = !actual.IsZero()
default:
@@ -88,10 +88,10 @@ func (*Namespace) Default(dflt any, given ...any) (any, error) {
}
if set {
return given[0], nil
return givenv[0], nil
}
return dflt, nil
return defaultv, nil
}
// Eq returns the boolean truth of arg1 == arg2 || arg1 == arg3 || arg1 == arg4.
@@ -223,12 +223,13 @@ func (n *Namespace) checkComparisonArgCount(min int, others ...any) bool {
}
// Conditional can be used as a ternary operator.
// It returns a if condition, else b.
func (n *Namespace) Conditional(condition bool, a, b any) any {
if condition {
return a
//
// It returns v1 if cond is true, else v2.
func (n *Namespace) Conditional(cond bool, v1, v2 any) any {
if cond {
return v1
}
return b
return v2
}
func (ns *Namespace) compareGet(a any, b any) (float64, float64) {