about summary refs log tree commit diff stats
path: root/gomponents.go
diff options
context:
space:
mode:
authorMarkus Wüstenberg2020-10-22 09:07:57 +0200
committerGitHub2020-10-22 09:07:57 +0200
commit6d2fb0eeb15d6b9774f127517d160137251264a4 (patch)
treed571a516f25e85dd4086521d73a419573d776df2 /gomponents.go
parentf2a2b949704e2faa7117dd33aae8da551a4baf8e (diff)
downloadgomponents-6d2fb0eeb15d6b9774f127517d160137251264a4.tar.lz
gomponents-6d2fb0eeb15d6b9774f127517d160137251264a4.tar.zst
gomponents-6d2fb0eeb15d6b9774f127517d160137251264a4.zip
Add Group function to group Nodes (#29)
Diffstat (limited to 'gomponents.go')
-rw-r--r--gomponents.go47
1 files changed, 36 insertions, 11 deletions
diff --git a/gomponents.go b/gomponents.go
index 52d5355..c0aa510 100644
--- a/gomponents.go
+++ b/gomponents.go
@@ -64,17 +64,7 @@ func El(name string, children ...Node) NodeFunc {
 		}
 
 		for _, c := range children {
-			if p, ok := c.(Placer); ok {
-				switch p.Place() {
-				case Inside:
-					inside.WriteString(c.Render())
-				case Outside:
-					outside.WriteString(c.Render())
-				}
-				continue
-			}
-			// If c doesn't implement Placer, default to outside
-			outside.WriteString(c.Render())
+			renderChild(c, &inside, &outside)
 		}
 
 		b.WriteString(inside.String())
@@ -93,6 +83,26 @@ func El(name string, children ...Node) NodeFunc {
 	}
 }
 
+func renderChild(c Node, inside, outside *strings.Builder) {
+	if g, ok := c.(group); ok {
+		for _, groupC := range g.children {
+			renderChild(groupC, inside, outside)
+		}
+		return
+	}
+	if p, ok := c.(Placer); ok {
+		switch p.Place() {
+		case Inside:
+			inside.WriteString(c.Render())
+		case Outside:
+			outside.WriteString(c.Render())
+		}
+		return
+	}
+	// If c doesn't implement Placer, default to outside
+	outside.WriteString(c.Render())
+}
+
 // Attr creates an attr DOM Node.
 // If one parameter is passed, it's a name-only attribute (like "required").
 // If two parameters are passed, it's a name-value attribute (like `class="header"`).
@@ -156,3 +166,18 @@ func Write(w io.Writer, n Node) error {
 	_, err := w.Write([]byte(n.Render()))
 	return err
 }
+
+type group struct {
+	children []Node
+}
+
+func (g group) Render() string {
+	panic("cannot render group")
+}
+
+// Group multiple Nodes into one Node. Useful for concatenation of Nodes in variadic functions.
+// The resulting Node cannot Render directly, trying it will panic.
+// Render must happen through a parent element created with El or a helper.
+func Group(children []Node) Node {
+	return group{children: children}
+}