Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fragment element #145

Merged
merged 1 commit into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading