shithub: hugo

Download patch

ref: 0462c96a5a9da3e8adc78d96acd39575a8b46c40
parent: 202510fdc92d52a20baeaa7edb1091f6882bd95f
author: Bjørn Erik Pedersen <[email protected]>
date: Fri Sep 8 10:16:21 EDT 2017

tpl/compare: Add cond (ternary) template func

Fixes #3860

--- a/tpl/compare/compare.go
+++ b/tpl/compare/compare.go
@@ -142,6 +142,15 @@
 	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
--- a/tpl/compare/compare_test.go
+++ b/tpl/compare/compare_test.go
@@ -221,3 +221,12 @@
 		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))
+}
--- a/tpl/compare/init.go
+++ b/tpl/compare/init.go
@@ -69,6 +69,13 @@
 			[][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
 
 	}