From f22ce3fb68ca6702a683b7759410ae50a9fddabd Mon Sep 17 00:00:00 2001 From: Markus Wüstenberg Date: Tue, 22 Dec 2020 10:53:22 +0100 Subject: Add If helper function (#57) Used to inline conditional nodes.--- components/elements.go | 10 ++++++++++ gomponents.go | 19 ++++++++++++++++--- gomponents_test.go | 12 ++++++++++++ 3 files changed, 38 insertions(+), 3 deletions(-) create mode 100644 components/elements.go diff --git a/components/elements.go b/components/elements.go new file mode 100644 index 0000000..baffba6 --- /dev/null +++ b/components/elements.go @@ -0,0 +1,10 @@ +package components + +import ( + g "github.com/maragudk/gomponents" + . "github.com/maragudk/gomponents/html" +) + +func InputHidden(name, value string, children ...g.Node) g.NodeFunc { + return Input(Type("hidden"), Name(name), Value(value), g.Group(children)) +} diff --git a/gomponents.go b/gomponents.go index de46b7c..1986a1e 100644 --- a/gomponents.go +++ b/gomponents.go @@ -222,11 +222,11 @@ func Group(children []Node) Node { // Example: // items := []string{"hat", "partyhat"} // -// lis := g.Map(len(items), func(i int) g.Node { -// return g.El("li", g.Text(items[i])) +// lis := Map(len(items), func(i int) Node { +// return El("li", Text(items[i])) // }) // -// list := g.El("ul", lis...) +// list := El("ul", lis...) func Map(length int, cb func(i int) Node) []Node { var nodes []Node for i := 0; i < length; i++ { @@ -234,3 +234,16 @@ func Map(length int, cb func(i int) Node) []Node { } return nodes } + +// If condition is true, return the given Node. Otherwise, return nil. +// This helper function is good for inlining elements conditionally. +// Example: +// El("div", +// If(showMessage, El("span", "You lost your hat.")), +// ) +func If(condition bool, n Node) Node { + if condition { + return n + } + return nil +} diff --git a/gomponents_test.go b/gomponents_test.go index 26199c3..c88a796 100644 --- a/gomponents_test.go +++ b/gomponents_test.go @@ -207,3 +207,15 @@ func TestMap(t *testing.T) { assert.Equal(t, `