-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml.go
213 lines (200 loc) · 6.01 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package render
import (
"fmt"
"html/template"
"io"
"net/http"
"os"
"strconv"
)
var funcMap template.FuncMap
func toString(i any) (string, error) {
switch v := i.(type) {
case string:
return v, nil
case bool:
return strconv.FormatBool(v), nil
case float64:
return strconv.FormatFloat(v, 'f', -1, 64), nil
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32), nil
case int:
return strconv.Itoa(v), nil
case int64:
return strconv.FormatInt(v, 10), nil
case int32:
return strconv.Itoa(int(v)), nil
case int16:
return strconv.FormatInt(int64(v), 10), nil
case int8:
return strconv.FormatInt(int64(v), 10), nil
case uint:
return strconv.FormatInt(int64(v), 10), nil
case uint64:
return strconv.FormatInt(int64(v), 10), nil
case uint32:
return strconv.FormatInt(int64(v), 10), nil
case uint16:
return strconv.FormatInt(int64(v), 10), nil
case uint8:
return strconv.FormatInt(int64(v), 10), nil
case []byte:
return string(v), nil
case template.CSS:
return string(v), nil
case template.HTML:
return string(v), nil
case template.HTMLAttr:
return string(v), nil
case template.JS:
return string(v), nil
case template.JSStr:
return string(v), nil
case template.URL:
return string(v), nil
case template.Srcset:
return string(v), nil
case nil:
return "", nil
case fmt.Stringer:
return v.String(), nil
case error:
return v.Error(), nil
default:
return "", fmt.Errorf("cast error; value: %#v, type: %T", i, i)
}
}
func init() {
funcMap = template.FuncMap{
"day": dayFn,
"date": dateFn,
"datetime": datetimeFn,
"default": defaultFn,
"dict": dictFn,
"eval": evalFn,
"findRE": findREFn,
"in": inFn,
"index": indexFn,
"len": lenFn,
"lower": lowerFn,
"map": mapFn,
"month": monthFn,
"replace": replaceFn,
"replaceRE": replaceREFn,
"safeCSS": safeCSSFn,
"safeHTML": safeHTMLFn,
"safeHTMLAttr": safeHTMLAttrFn,
"safeJS": safeJSFn,
"safeURL": safeURLFn,
"slice": sliceFn,
"split": splitFn,
"time": timeFn,
"trim": trimFn,
"trimLeft": trimLeftFn,
"trimRight": trimRightFn,
"upper": upperFn,
"year": yearFn,
}
}
// HTML renders the template as HTML to the provided io.Writer.
//
// Deprecated: Use Template.HTML method instead.
func HTML(w io.Writer, status int, data any, layout string, ext ...string) {
files := append([]string{layout}, ext...)
for i := range files {
files[i] = "templates/" + files[i] + ".html"
}
tmpl := template.Must(template.New(layout + ".html").Funcs(funcMap).ParseFiles(files...))
if hw, ok := w.(http.ResponseWriter); ok {
if err := tmpl.ExecuteTemplate(w, layout, data); err != nil {
http.Error(hw, err.Error(), http.StatusInternalServerError)
} else {
hw.Header().Set("Content-Type", "text/html")
hw.WriteHeader(status)
}
}
}
// Template represents a web template that includes references to OS files, embedded files,
// a layout, data, and additional functions.
//
// This structure holds the necessary components to render a web page, including references to OS files,
// embedded files (using http.File from an embed.FS), a layout template, data to be rendered,
// and additional template functions.
//
// Fields:
// - OsFiles: A slice of pointers to os.File objects representing files to be read from the filesystem.
// - HttpFiles: A slice of http.File objects representing embedded files accessible via the http package.
// - Layout: The name of the layout template to be used with html/template.ExecuteTemplate for rendering.
// - Data: The data to be passed to the template for rendering.
// - ExtraFuncMap: A map of additional functions to be used in the template, extending
// the default template functionality.
//
// Example usage:
//
// tmpl := Template{
// OsFiles: []*os.File{file1, file2},
// HttpFiles: []http.File{httpFile1, httpFile2},
// Layout: "layout", // This is the name of the layout template, not a file name.
// Data: myData,
// ExtraFuncMap: template.FuncMap{
// "customFunc": func() string { return "Custom Function" },
// },
// }
//
// This structure allows for flexible and powerful rendering of web pages, supporting
// a wide range of use cases including the inclusion of both local and embedded files,
// custom data, and additional template functions.
type Template struct {
OsFiles []*os.File
HttpFiles []http.File
Layout string
Data any
ExtraFuncMap template.FuncMap
}
// HTML renders the template as HTML to the provided io.Writer.
//
// This method takes an io.Writer (typically an http.ResponseWriter) and an HTTP status code.
// It renders the template with the given data and writes the resulting HTML to the writer.
// The HTTP status code is set on the http.ResponseWriter to indicate the response status.
//
// Parameters:
// - w: io.Writer to which the rendered HTML will be written. This is usually an http.ResponseWriter.
// - status: HTTP status code to set on the http.ResponseWriter.
//
// Example usage:
//
// func handler(w http.ResponseWriter, r *http.Request) {
// tmpl := Template{
// Layout: "layout.html",
// Data: myData,
// }
// tmpl.HTML(w, http.StatusOK)
// }
func (t Template) HTML(w io.Writer, status int) {
tmpl := template.New(t.Layout)
funcMap["dtemplate"] = dynamicTemplateFn(tmpl)
tmpl.Funcs(funcMap)
if len(t.ExtraFuncMap) > 0 {
tmpl.Funcs(t.ExtraFuncMap)
}
for i := range t.OsFiles {
buf, _ := io.ReadAll(t.OsFiles[i])
if t, err := tmpl.Parse(string(buf)); err == nil {
tmpl = t
}
}
for i := range t.HttpFiles {
buf, _ := io.ReadAll(t.HttpFiles[i])
if t, err := tmpl.Parse(string(buf)); err == nil {
tmpl = t
}
}
if hw, ok := w.(http.ResponseWriter); ok {
if err := tmpl.ExecuteTemplate(w, t.Layout, t.Data); err != nil {
http.Error(hw, err.Error(), http.StatusInternalServerError)
} else {
hw.Header().Set("Content-Type", "text/html")
hw.WriteHeader(status)
}
}
}