all repos — gomponents @ 5eae1eef0f0a090ae569a23c0c52db356a109cfc

HTML components in pure Go

Add else part to If/Iff

Alan Pearce
commit

5eae1eef0f0a090ae569a23c0c52db356a109cfc

parent

6aea6d0965f9030d598eb87f5bfca36b638035f6

1 file changed, 22 insertions(+), 3 deletions(-)

changed files
M gomponents.gogomponents.go
@@ -298,20 +298,39 @@ // If condition is true, return the given [Node]. Otherwise, return nil.
// This helper function is good for inlining elements conditionally. // If it's important that the given [Node] is only evaluated if condition is true // (for example, when using nilable variables), use [Iff] instead. -func If(condition bool, n Node) Node { +func If(condition bool, n Node, otherwise ...Node) Node { + var o Node + switch len(otherwise) { + case 0: + case 1: + o = otherwise[0] + default: + panic("If must have just one or two nodes") + } if condition { return n } - return nil + return o } // Iff condition is true, call the given function. Otherwise, return nil. // This helper function is good for inlining elements conditionally when the node depends on nilable data, // or some other code that could potentially panic. // If you just need simple conditional rendering, see [If]. -func Iff(condition bool, f func() Node) Node { +func Iff(condition bool, f func() Node, otherwise ...func() Node) Node { + var o func() Node + switch len(otherwise) { + case 0: + case 1: + o = otherwise[0] + default: + panic("Iff must have just one or two nodes") + } if condition { return f() + } + if o != nil { + return o() } return nil }