-
Notifications
You must be signed in to change notification settings - Fork 0
/
element.go
82 lines (66 loc) · 1.33 KB
/
element.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
package htmlbuilder
import (
"bytes"
"html"
)
type Renderer interface {
Render() string
}
type Element struct {
name string
elementBuff bytes.Buffer
attributeBuff bytes.Buffer
content []Renderer
}
func (e *Element) Render() string {
e.elementBuff.Reset()
e.attributeBuff.Reset()
buff := bytes.Buffer{}
buff.WriteString("<" + e.name)
for _, c := range e.content {
switch c.(type) {
case *Element:
e.elementBuff.WriteString(c.Render())
case *InnerText:
e.elementBuff.WriteString(c.Render())
case *Attribute:
e.attributeBuff.WriteString(" " + c.Render())
}
}
if e.attributeBuff.Len() > 0 {
buff.WriteString(e.attributeBuff.String())
}
buff.WriteString(">")
buff.WriteString(e.elementBuff.String())
buff.WriteString("</" + e.name + ">")
return buff.String()
}
func NewElement(name string, content ...Renderer) *Element {
return &Element{
name: name,
content: content,
}
}
type Attribute struct {
key string
value string
}
func (a *Attribute) Render() string {
return a.key + "=\"" + html.EscapeString(a.value) + "\""
}
func Attr(key, value string) *Attribute {
return &Attribute{
key: key,
value: value,
}
}
type InnerText struct {
text string
isUnsafe bool
}
func (i *InnerText) Render() string {
if i.isUnsafe {
return i.text
}
return html.EscapeString(i.text)
}