about summary refs log tree commit diff stats
path: root/el
diff options
context:
space:
mode:
authorMarkus Wüstenberg2020-11-02 10:03:05 +0100
committerGitHub2020-11-02 10:03:05 +0100
commit6c8f0c235287edf7252fe239d4c9beb258c6ff01 (patch)
treeae1245a8e1491f5f369e8d9ef2517148d9774130 /el
parent92ba5904c1645e6572f5ff1b9d0e0ec629e1afb9 (diff)
downloadgomponents-6c8f0c235287edf7252fe239d4c9beb258c6ff01.tar.lz
gomponents-6c8f0c235287edf7252fe239d4c9beb258c6ff01.tar.zst
gomponents-6c8f0c235287edf7252fe239d4c9beb258c6ff01.zip
Render to Writer instead of string (#39)
The Render function has been changed to take a `Writer` instead of returning a string. This makes it possible to generate documents without having the whole content in memory.

This also removes the `gomponents.Write` function, which is now redundant.

Furthermore, the `el.Document` function has been changed to only take one child, as multiple children never make sense for it. (It's not even a child, more a sibling.)
Diffstat (limited to 'el')
-rw-r--r--el/elements.go16
-rw-r--r--el/elements_test.go12
2 files changed, 19 insertions, 9 deletions
diff --git a/el/elements.go b/el/elements.go
index 4ca001f..0841ff8 100644
--- a/el/elements.go
+++ b/el/elements.go
@@ -4,7 +4,7 @@ package el
 
 import (
 	"fmt"
-	"strings"
+	"io"
 
 	g "github.com/maragudk/gomponents"
 )
@@ -13,15 +13,13 @@ func A(href string, children ...g.Node) g.NodeFunc {
 	return g.El("a", g.Attr("href", href), g.Group(children))
 }
 
-// Document returns an special kind of Node that prefixes its children with the string "<!doctype html>".
-func Document(children ...g.Node) g.NodeFunc {
-	return func() string {
-		var b strings.Builder
-		b.WriteString("<!doctype html>")
-		for _, c := range children {
-			b.WriteString(c.Render())
+// Document returns an special kind of Node that prefixes its child with the string "<!doctype html>".
+func Document(child g.Node) g.NodeFunc {
+	return func(w io.Writer) error {
+		if _, err := w.Write([]byte("<!doctype html>")); err != nil {
+			return err
 		}
-		return b.String()
+		return child.Render(w)
 	}
 }
 
diff --git a/el/elements_test.go b/el/elements_test.go
index 6c73188..e90be9f 100644
--- a/el/elements_test.go
+++ b/el/elements_test.go
@@ -1,6 +1,7 @@
 package el_test
 
 import (
+	"errors"
 	"testing"
 
 	g "github.com/maragudk/gomponents"
@@ -8,10 +9,21 @@ import (
 	"github.com/maragudk/gomponents/el"
 )
 
+type erroringWriter struct{}
+
+func (w *erroringWriter) Write(p []byte) (n int, err error) {
+	return 0, errors.New("don't want to write")
+}
+
 func TestDocument(t *testing.T) {
 	t.Run("returns doctype and children", func(t *testing.T) {
 		assert.Equal(t, `<!doctype html><html />`, el.Document(g.El("html")))
 	})
+
+	t.Run("errors on write error in Render", func(t *testing.T) {
+		err := el.Document(g.El("html")).Render(&erroringWriter{})
+		assert.Error(t, err)
+	})
 }
 
 func TestForm(t *testing.T) {