Skip to content

Commit

Permalink
Change to string builder
Browse files Browse the repository at this point in the history
  • Loading branch information
chasefleming committed Oct 13, 2023
1 parent 73a2e5c commit 81b497a
Showing 1 changed file with 29 additions and 13 deletions.
42 changes: 29 additions & 13 deletions elem.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package elem

import (
"sort"
"strings"
)

// List of HTML5 void elements. Void elements, also known as self-closing or empty elements,
Expand Down Expand Up @@ -35,6 +36,11 @@ type Element struct {
}

func (e *Element) Render() string {
var builder strings.Builder

// Start with opening tag
builder.WriteString("<")
builder.WriteString(e.Tag)

// Sort the keys for consistent order
keys := make([]string, 0, len(e.Attrs))
Expand All @@ -43,30 +49,40 @@ func (e *Element) Render() string {
}
sort.Strings(keys)

props := ""
// Append the attributes to the builder
for _, k := range keys {
props += ` ` + k + `="` + e.Attrs[k] + `"`
builder.WriteString(` `)
builder.WriteString(k)
builder.WriteString(`="`)
builder.WriteString(e.Attrs[k])
builder.WriteString(`"`)
}

// If it's a void element, close it and return
if _, exists := voidElements[e.Tag]; exists {
builder.WriteString(`>`)
return builder.String()
}

content := ""
// Close opening tag
builder.WriteString(`>`)

// Build the content (either child text or nested elements)
for _, child := range e.Children {
switch c := child.(type) {
case string:
content += c
builder.WriteString(c)
case *Element:
content += c.Render()
builder.WriteString(c.Render())
}
}

// Check if the tag is a void element and doesn't have any content
if content == "" {
_, exists := voidElements[e.Tag]
if exists {
return `<` + e.Tag + props + `>` // No closing tag for void elements
}
}
// Append closing tag
builder.WriteString(`</`)
builder.WriteString(e.Tag)
builder.WriteString(`>`)

return `<` + e.Tag + props + `>` + content + `</` + e.Tag + `>`
return builder.String()
}

func NewElement(tag string, attrs Attrs, children ...interface{}) *Element {
Expand Down

0 comments on commit 81b497a

Please sign in to comment.