-
Notifications
You must be signed in to change notification settings - Fork 0
/
html.go
executable file
·95 lines (70 loc) · 1.51 KB
/
html.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package common
import (
"fmt"
"html"
"strings"
)
type Element struct {
Name string
Text string
Attrs *OrderedMap[string, string]
Elements []*Element
}
func NewElement(name string) *Element {
return &Element{
Name: name,
Attrs: NewOrderedMap[string, string](),
}
}
func (e *Element) String() string {
sb := strings.Builder{}
if e.IsTextOnly() {
if e.Text != "" {
sb.WriteString(html.EscapeString(e.Text))
}
return sb.String()
}
sb.WriteString(fmt.Sprintf("<%s", e.Name))
if e.Text == "" && e.Attrs.Len() == 0 {
sb.WriteString("/>")
return sb.String()
}
e.Attrs.Range(func(k string, v string) {
if sb.Len() > 0 {
sb.WriteString(" ")
}
if v == "" {
sb.WriteString(k)
} else {
sb.WriteString(fmt.Sprintf("%s=\"%s\"", k, html.EscapeString(v)))
}
})
sb.WriteString(">")
for _, element := range e.Elements {
sb.WriteString(element.String())
}
if e.Text != "" {
sb.WriteString(html.EscapeString(e.Text))
}
sb.WriteString(fmt.Sprintf("</%s>", e.Name))
return sb.String()
}
func (e *Element) IsTextOnly() bool {
return e.Name == ""
}
func (e *Element) AddElement(element *Element) *Element {
e.Elements = append(e.Elements, element)
return element
}
func (e *Element) RemoveElement(element *Element) *Element {
e.Elements = append(e.Elements, element)
return e
}
func (e *Element) AddAttr(name string, value string) *Element {
e.Attrs.Add(name, value)
return e
}
func (e *Element) RemoveAttr(name string) *Element {
e.Attrs.Remove(name)
return e
}