-
Notifications
You must be signed in to change notification settings - Fork 0
/
html.go
110 lines (86 loc) · 1.97 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"strings"
"text/template"
)
type Attr struct {
Key string
Value string
}
// Doc is short for document
func Doc(children ...string) string {
builder := strings.Builder{}
builder.WriteString("<!doctype html>")
for _, child := range children {
builder.WriteString(child)
}
return builder.String()
}
// El is short for element
func El(name string, children ...string) string {
return createElement(name, nil, false, children...)
}
// Ela is short for element with attributes
func Ela(name string, attributes []Attr, children ...string) string {
return createElement(name, attributes, false, children...)
}
// Sela is short for self-closing element with attributes
func Sela(name string, attributes []Attr) string {
return createElement(name, attributes, true)
}
func createElement(name string, attributes []Attr, selfClosing bool, children ...string) string {
builder := strings.Builder{}
builder.WriteString("<")
builder.WriteString(name)
for _, attr := range attributes {
builder.WriteString(" ")
builder.WriteString(attr.Key)
builder.WriteString(`="`)
builder.WriteString(attr.Value)
builder.WriteString(`"`)
}
builder.WriteString(">")
if !selfClosing {
for _, child := range children {
builder.WriteString(child)
}
builder.WriteString("</")
builder.WriteString(name)
builder.WriteString(">")
}
return builder.String()
}
func If(cond bool, s string) string {
if cond {
return s
}
return ""
}
func IfComputed(cond bool, f func() string) string {
if cond {
return f()
}
return ""
}
func IfElse(cond bool, a, b string) string {
if cond {
return a
}
return b
}
func IfElseComputed(cond bool, a, b func() string) string {
if cond {
return a()
}
return b()
}
func ForEach[T any](arr []T, f func(index int, value T) string) string {
builder := strings.Builder{}
for i, v := range arr {
builder.WriteString(f(i, v))
}
return builder.String()
}
func Esc(s string) string {
return template.HTMLEscapeString(s)
}