From 0462c96a5a9da3e8adc78d96acd39575a8b46c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Pedersen?= Date: Fri, 8 Sep 2017 14:16:21 +0200 Subject: [PATCH] tpl/compare: Add cond (ternary) template func Fixes #3860 --- tpl/compare/compare.go | 9 +++++++++ tpl/compare/compare_test.go | 9 +++++++++ tpl/compare/init.go | 7 +++++++ 3 files changed, 25 insertions(+) diff --git a/tpl/compare/compare.go b/tpl/compare/compare.go index 2df03b7db..65228da99 100644 --- a/tpl/compare/compare.go +++ b/tpl/compare/compare.go @@ -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 diff --git a/tpl/compare/compare_test.go b/tpl/compare/compare_test.go index 9adbcf574..c9bc2ffe9 100644 --- a/tpl/compare/compare_test.go +++ b/tpl/compare/compare_test.go @@ -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)) +} diff --git a/tpl/compare/init.go b/tpl/compare/init.go index fbc5e1fda..7d58cf9ab 100644 --- a/tpl/compare/init.go +++ b/tpl/compare/init.go @@ -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 }