Skip to content

Commit

Permalink
Add Func type
Browse files Browse the repository at this point in the history
`Func` is a function that returns a `Node` that is itself also a `Node`.

Used with `If`, it enables lazy evaluation of the node to return, depending on the condition passed to `If`.

See also #99 for a different approach explored.
  • Loading branch information
markuswustenberg committed May 25, 2022
1 parent 9769861 commit f4a6ff5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
9 changes: 9 additions & 0 deletions gomponents.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,12 @@ func If(condition bool, n Node) Node {
}
return nil
}

// Func is a function that returns a Node that is itself also a Node.
// Used with If, it enables lazy evaluation of the node to return, depending on the condition passed to If.
type Func func() Node

// Render implements Node.
func (f Func) Render(w io.Writer) error {
return f().Render(w)
}
20 changes: 20 additions & 0 deletions gomponents_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,23 @@ func ExampleIf() {
_ = e.Render(os.Stdout)
// Output: <div><span>You lost your hat!</span></div>
}

func TestFunc(t *testing.T) {
t.Run("Func is a function type that is also a Node", func(t *testing.T) {
n := g.Func(func() g.Node {
return g.El("div")
})
assert.Equal(t, "<div></div>", n)
})
}

func ExampleIf_func() {
var message *string
e := g.El("div",
g.If(message != nil, g.Func(func() g.Node {
return g.El("span", g.Text(*message))
})),
)
_ = e.Render(os.Stdout)
// Output: <div></div>
}

0 comments on commit f4a6ff5

Please sign in to comment.