about summary refs log tree commit diff stats
path: root/gomponents.go
diff options
context:
space:
mode:
authorMarkus Wüstenberg2020-11-02 10:59:16 +0100
committerGitHub2020-11-02 10:59:16 +0100
commit267d40bbea6036f913c4047a6a2055b3e5d7bb96 (patch)
treeef2bcb5be63bb6f9fdfd6a608698473ac2192ea6 /gomponents.go
parent6c8f0c235287edf7252fe239d4c9beb258c6ff01 (diff)
downloadgomponents-267d40bbea6036f913c4047a6a2055b3e5d7bb96.tar.lz
gomponents-267d40bbea6036f913c4047a6a2055b3e5d7bb96.tar.zst
gomponents-267d40bbea6036f913c4047a6a2055b3e5d7bb96.zip
Add Map function (#40)
`Map` makes it easier to build lists of elements without having to iterate.
Diffstat (limited to 'gomponents.go')
-rw-r--r--gomponents.go17
1 files changed, 17 insertions, 0 deletions
diff --git a/gomponents.go b/gomponents.go
index 178f0a2..02e52ca 100644
--- a/gomponents.go
+++ b/gomponents.go
@@ -217,3 +217,20 @@ func (g group) Render(io.Writer) error {
 func Group(children []Node) Node {
 	return group{children: children}
 }
+
+// Map something enumerable to a list of Nodes.
+// Example:
+// 	items := []string{"hat", "partyhat"}
+//
+// 	lis := g.Map(len(items), func(i int) g.Node {
+// 		return g.El("li", g.Text(items[i]))
+// 	})
+//
+// 	list := g.El("ul", lis...)
+func Map(length int, cb func(i int) Node) []Node {
+	var nodes []Node
+	for i := 0; i < length; i++ {
+		nodes = append(nodes, cb(i))
+	}
+	return nodes
+}