Skip to content

Commit

Permalink
Merge pull request #145 from goring/main
Browse files Browse the repository at this point in the history
Add fragment element
  • Loading branch information
chasefleming authored Aug 15, 2024
2 parents d709650 + 9126536 commit bdff672
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 8 deletions.
24 changes: 16 additions & 8 deletions elem.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,13 @@ func (e *Element) RenderTo(builder *strings.Builder, opts RenderOptions) {
builder.WriteString("<!DOCTYPE html>")
}

isFragment := e.Tag == "fragment"

// Start with opening tag
builder.WriteString("<")
builder.WriteString(e.Tag)
if !isFragment {
builder.WriteString("<")
builder.WriteString(e.Tag)
}

// Sort the keys for consistent order
keys := make([]string, 0, len(e.Attrs))
Expand All @@ -170,18 +174,22 @@ func (e *Element) RenderTo(builder *strings.Builder, opts RenderOptions) {
return
}

// Close opening tag
builder.WriteString(`>`)
if !isFragment {
// Close opening tag
builder.WriteString(`>`)
}

// Build the content
for _, child := range e.Children {
child.RenderTo(builder, opts)
}

// Append closing tag
builder.WriteString(`</`)
builder.WriteString(e.Tag)
builder.WriteString(`>`)
if !isFragment {
// Append closing tag
builder.WriteString(`</`)
builder.WriteString(e.Tag)
builder.WriteString(`>`)
}
}

// return string representation of given attribute with its value
Expand Down
5 changes: 5 additions & 0 deletions elements.go
Original file line number Diff line number Diff line change
Expand Up @@ -530,3 +530,8 @@ func Raw(html string) RawNode {
func CSS(content string) TextNode {
return TextNode(content)
}

// Fragments are a way to group multiple elements together without adding an extra node to the DOM.
func Fragment(children ...Node) *Element {
return newElement("fragment", attrs.Props{}, children...)
}
29 changes: 29 additions & 0 deletions elements_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -696,3 +696,32 @@ func TestSingleQuote(t *testing.T) {
actual := el.Render()
assert.Equal(t, expected, actual)
}

func TestFragment(t *testing.T) {
expected := `<div><p>0</p><p>1</p><p>2</p><p>3</p><p>4</p></div>`
nodes1 := []Node{
P(nil,
Text("1"),
),
P(nil,
Text("2"),
),
}
nodes2 := []Node{
P(nil,
Text("3"),
),
P(nil,
Text("4"),
),
}
el := Div(nil,
P(nil,
Text("0"),
),
Fragment(nodes1...),
Fragment(nodes2...),
)
actual := el.Render()
assert.Equal(t, expected, actual)
}

0 comments on commit bdff672

Please sign in to comment.