tpl/compare: Add cond (ternary) template func
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 8 Sep 2017 12:16:21 +0000 (14:16 +0200)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 8 Sep 2017 14:59:43 +0000 (16:59 +0200)
Fixes #3860

tpl/compare/compare.go
tpl/compare/compare_test.go
tpl/compare/init.go

index 2df03b7dbadd2e7c520150ed75e144933085979d..65228da995c18142e752b8c93171a1cdef6383dd 100644 (file)
@@ -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
index 9adbcf5749e60be2c85dc8b13361756e40d6d3b4..c9bc2ffe9324e66c76d583104f627d5575530a66 100644 (file)
@@ -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))
+}
index fbc5e1fda98239e4122db1d26c52be9f7a2c502e..7d58cf9aba73dea9ce80b5af4b25d57932bc5ca6 100644 (file)
@@ -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
 
        }