diff options
author | Alan Pearce | 2025-03-19 11:50:50 +0100 |
---|---|---|
committer | Alan Pearce | 2025-03-19 12:03:53 +0100 |
commit | 5eae1eef0f0a090ae569a23c0c52db356a109cfc (patch) | |
tree | 0e01e7dfa606f00843d02447688b280924d9f06f /gomponents.go | |
parent | 6aea6d0965f9030d598eb87f5bfca36b638035f6 (diff) | |
download | gomponents-5eae1eef0f0a090ae569a23c0c52db356a109cfc.tar.lz gomponents-5eae1eef0f0a090ae569a23c0c52db356a109cfc.tar.zst gomponents-5eae1eef0f0a090ae569a23c0c52db356a109cfc.zip |
Add else part to If/Iff
Diffstat (limited to 'gomponents.go')
-rw-r--r-- | gomponents.go | 25 |
1 files changed, 22 insertions, 3 deletions
diff --git a/gomponents.go b/gomponents.go index 37267d4..4867152 100644 --- a/gomponents.go +++ b/gomponents.go @@ -298,20 +298,39 @@ func (g Group) Render(w io.Writer) error { // 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 } |