Permalink
Browse files

tpl/compare: Add cond (ternary) template func

Fixes #3860
  • Loading branch information...
bep committed Sep 8, 2017
1 parent 202510f commit 0462c96a5a9da3e8adc78d96acd39575a8b46c40
Showing with 25 additions and 0 deletions.
  1. +9 −0 tpl/compare/compare.go
  2. +9 −0 tpl/compare/compare_test.go
  3. +7 −0 tpl/compare/init.go
View
@@ -142,6 +142,15 @@ func (n *Namespace) Lt(a, b interface{}) bool {
return left < right
}
// Conditional can be used as a ternary operator.
// It returns a if condition, else b.
func (n *Namespace) Conditional(condition bool, a, b interface{}) interface{} {
if condition {
return a
}
return b
}
func (*Namespace) compareGetFloat(a interface{}, b interface{}) (float64, float64) {
var left, right float64
var leftStr, rightStr *string
@@ -221,3 +221,12 @@ func TestTimeUnix(t *testing.T) {
toTimeUnix(iv)
}(t)
}
func TestConditional(t *testing.T) {
assert := require.New(t)
n := New()
a, b := "a", "b"
assert.Equal(a, n.Conditional(true, a, b))
assert.Equal(b, n.Conditional(false, a, b))
}
View
@@ -69,6 +69,13 @@ func init() {
[][2]string{},
)
ns.AddMethodMapping(ctx.Conditional,
[]string{"cond"},
[][2]string{
{`{{ cond (eq (add 2 2) 4) "2+2 is 4" "what?" | safeHTML }}`, `2+2 is 4`},
},
)
return ns
}

0 comments on commit 0462c96

Please sign in to comment.