Add RenderableGroup function for rendering a group of nodes without a parent element

This commit is contained in:
Luis Eduardo Jeréz Girón
2024-07-23 21:40:12 -06:00
parent 7b5aac953b
commit eaee34b227
2 changed files with 68 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
package component
import (
"bytes"
"github.com/maragudk/gomponents"
)
// RenderableGroup renders a group of nodes without a parent element.
//
// This is because gomponents.Group() cannot be directly rendered and
// needs to be wrapped in a parent element.
func RenderableGroup(children []gomponents.Node) gomponents.Node {
buf := bytes.Buffer{}
for _, child := range children {
err := child.Render(&buf)
if err != nil {
return gomponents.Raw("Error rendering group")
}
}
return gomponents.Raw(buf.String())
}

View File

@@ -0,0 +1,46 @@
package component
import (
"bytes"
"testing"
"github.com/maragudk/gomponents"
"github.com/maragudk/gomponents/html"
"github.com/stretchr/testify/assert"
)
func TestRenderableGroupRenderer(t *testing.T) {
t.Run("renders a group of string nodes without a parent element", func(t *testing.T) {
gotRenderer := RenderableGroup([]gomponents.Node{
gomponents.Text("foo"),
gomponents.Text("bar"),
})
got := bytes.Buffer{}
err := gotRenderer.Render(&got)
assert.NoError(t, err)
expected := "foobar"
assert.Equal(t, expected, got.String())
})
t.Run("renders a group of tag nodes without a parent element", func(t *testing.T) {
gotRenderer := RenderableGroup([]gomponents.Node{
html.Span(
gomponents.Text("foo"),
),
html.P(
gomponents.Text("bar"),
),
})
got := bytes.Buffer{}
err := gotRenderer.Render(&got)
assert.NoError(t, err)
expected := `<span>foo</span><p>bar</p>`
assert.Equal(t, expected, got.String())
})
}