Skip to content

Commit 0462c96

Browse files
committed
tpl/compare: Add cond (ternary) template func
Fixes #3860
1 parent 202510f commit 0462c96

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

‎tpl/compare/compare.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,15 @@ func (n *Namespace) Lt(a, b interface{}) bool {
142142
return left < right
143143
}
144144

145+
// Conditional can be used as a ternary operator.
146+
// It returns a if condition, else b.
147+
func (n *Namespace) Conditional(condition bool, a, b interface{}) interface{} {
148+
if condition {
149+
return a
150+
}
151+
return b
152+
}
153+
145154
func (*Namespace) compareGetFloat(a interface{}, b interface{}) (float64, float64) {
146155
var left, right float64
147156
var leftStr, rightStr *string

‎tpl/compare/compare_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,12 @@ func TestTimeUnix(t *testing.T) {
221221
toTimeUnix(iv)
222222
}(t)
223223
}
224+
225+
func TestConditional(t *testing.T) {
226+
assert := require.New(t)
227+
n := New()
228+
a, b := "a", "b"
229+
230+
assert.Equal(a, n.Conditional(true, a, b))
231+
assert.Equal(b, n.Conditional(false, a, b))
232+
}

‎tpl/compare/init.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,13 @@ func init() {
6969
[][2]string{},
7070
)
7171

72+
ns.AddMethodMapping(ctx.Conditional,
73+
[]string{"cond"},
74+
[][2]string{
75+
{`{{ cond (eq (add 2 2) 4) "2+2 is 4" "what?" | safeHTML }}`, `2+2 is 4`},
76+
},
77+
)
78+
7279
return ns
7380

7481
}

0 commit comments

Comments
 (0)