-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtemplate.go
372 lines (317 loc) · 8.28 KB
/
template.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package hime
import (
"html/template"
"io"
"io/fs"
"os"
"path"
"strings"
"github.com/tdewolff/minify/v2"
"github.com/tdewolff/minify/v2/css"
"github.com/tdewolff/minify/v2/html"
"github.com/tdewolff/minify/v2/js"
"gopkg.in/yaml.v3"
)
// TemplateConfig is template config
type TemplateConfig struct {
Dir string `yaml:"dir" json:"dir"`
Root string `yaml:"root" json:"root"`
Minify bool `yaml:"minify" json:"minify"`
Preload []string `yaml:"preload" json:"preload"`
List map[string][]string `yaml:"list" json:"list"`
Delims []string `yaml:"delims" json:"delims"`
}
// Template creates new template loader
func (app *App) Template() *Template {
return &Template{
parent: template.Must(app.parent.Clone()),
list: app.template,
components: app.component,
}
}
// TemplateFuncs registers app's level template funcs
func (app *App) TemplateFuncs(funcs ...template.FuncMap) {
for _, f := range funcs {
app.parent.Funcs(f)
}
}
// TemplateFunc registers an app's level template func
func (app *App) TemplateFunc(name string, f any) {
app.TemplateFuncs(template.FuncMap{name: f})
}
type tmpl struct {
*template.Template
m *minify.M
}
func (t *tmpl) Execute(w io.Writer, data any) error {
// t.m.Writer is too slow for short data (html)
if t.m == nil {
return t.Template.Execute(w, data)
}
buf := getBytes()
defer putBytes(buf)
err := t.Template.Execute(buf, data)
if err != nil {
return err
}
return t.m.Minify("text/html", w, buf)
}
// Template is template loader
type Template struct {
parent *template.Template
list map[string]*tmpl
root string
fs fs.FS
dir string
components map[string]*tmpl
minifier *minify.M
}
// Config loads template config
func (tp *Template) Config(cfg TemplateConfig) {
tp.Dir(cfg.Dir)
tp.Root(cfg.Root)
if len(cfg.Delims) == 2 {
tp.Delims(cfg.Delims[0], cfg.Delims[1])
}
if cfg.Minify {
tp.Minify()
}
tp.Preload(cfg.Preload...)
for name, filenames := range cfg.List {
tp.ParseFiles(name, filenames...)
}
}
// ParseConfig parses template config data
func (tp *Template) ParseConfig(data []byte) {
var config TemplateConfig
err := yaml.Unmarshal(data, &config)
if err != nil {
panicf("can not parse template config; %v", err)
}
tp.Config(config)
}
// ParseConfigFile parses template config from file
func (tp *Template) ParseConfigFile(filename string) {
data, err := os.ReadFile(filename)
if err != nil {
panicf("read template config file; %v", err)
}
tp.ParseConfig(data)
}
type TemplateMinifyConfig struct {
HTML minify.Minifier
CSS minify.Minifier
JS minify.Minifier
}
// MinifyWith enables minify with custom options, must call before parse
func (tp *Template) MinifyWith(cfg TemplateMinifyConfig) {
tp.minifier = minify.New()
if cfg.HTML != nil {
tp.minifier.Add("text/html", cfg.HTML)
}
if cfg.CSS != nil {
tp.minifier.Add("text/css", cfg.CSS)
}
if cfg.JS != nil {
tp.minifier.Add("application/javascript", cfg.JS)
}
}
// Minify enables minify when render html, css, js, must call before parse
func (tp *Template) Minify() {
tp.MinifyWith(TemplateMinifyConfig{
HTML: &html.Minifier{},
CSS: &css.Minifier{},
JS: &js.Minifier{},
})
}
// Delims sets left and right delims
func (tp *Template) Delims(left, right string) {
tp.parent.Delims(left, right)
}
// Root calls t.Lookup(name) after load template,
// empty string won't trigger t.Lookup
//
// default is ""
func (tp *Template) Root(name string) {
tp.root = name
}
// Dir sets root directory when load template
//
// default is ""
func (tp *Template) Dir(path string) {
tp.dir = path
}
// FS uses fs when load template
func (tp *Template) FS(fs fs.FS) {
tp.fs = fs
}
// Funcs adds template funcs while load template
func (tp *Template) Funcs(funcs ...template.FuncMap) {
for _, f := range funcs {
tp.parent.Funcs(f)
}
}
// Func adds a template func while load template
func (tp *Template) Func(name string, f any) {
tp.Funcs(template.FuncMap{name: f})
}
// Preload loads given templates before parse
func (tp *Template) Preload(filename ...string) {
if len(filename) == 0 {
return
}
if tp.fs == nil {
template.Must(tp.parent.ParseFiles(joinTemplateDir(tp.dir, filename...)...))
} else {
template.Must(tp.parent.ParseFS(tp.fs, joinTemplateDir(tp.dir, filename...)...))
}
}
func (tp *Template) newTemplate(name string, parser func(t *template.Template) *template.Template) {
if _, ok := tp.list[name]; ok {
panic(newErrTemplateDuplicate(name))
}
t := template.Must(tp.parent.Clone()).
Funcs(template.FuncMap{
"templateName": func() string { return name },
})
t = parser(t)
if tp.root != "" {
t = t.Lookup(tp.root)
}
if t == nil {
panicf("no root layout")
}
tp.list[name] = &tmpl{
Template: t,
m: tp.minifier,
}
}
func (tp *Template) newComponent(name string, parser func(t *template.Template) *template.Template) {
if _, ok := tp.list[name]; ok {
panic(newErrComponentDuplicate(name))
}
t := template.Must(tp.parent.Clone()).
Funcs(template.FuncMap{
"componentName": func() string { return name },
})
t = parser(t)
if t == nil {
panicf("nil component")
}
tp.components[name] = &tmpl{
Template: t,
m: tp.minifier,
}
}
// Parse parses template from text
func (tp *Template) Parse(name string, text string) {
tp.newTemplate(name, func(t *template.Template) *template.Template {
return template.Must(t.New(name).Parse(text))
})
}
// ParseFiles loads template from file
func (tp *Template) ParseFiles(name string, filenames ...string) {
tp.newTemplate(name, func(t *template.Template) *template.Template {
if tp.fs == nil {
t = template.Must(t.ParseFiles(joinTemplateDir(tp.dir, filenames...)...))
} else {
t = template.Must(t.ParseFS(tp.fs, joinTemplateDir(tp.dir, filenames...)...))
}
if tp.root == "" {
t = t.Lookup(filenames[0])
}
return t
})
}
// ParseGlob loads template from pattern
func (tp *Template) ParseGlob(name string, pattern string) {
if tp.root == "" {
panicf("parse glob can not use without root")
}
tp.newTemplate(name, func(t *template.Template) *template.Template {
d := tp.dir
if !strings.HasSuffix(d, "/") {
d += "/"
}
if tp.fs == nil {
return template.Must(t.ParseGlob(d + pattern))
} else {
return template.Must(t.ParseFS(tp.fs, d+pattern))
}
})
}
// Component loads html/template into component list
func (tp *Template) Component(ts ...*template.Template) {
for _, t := range ts {
name := t.Name()
if name == "" {
panicf("can not load empty name component")
}
if _, ok := tp.components[name]; ok {
panicf("component '%s' already exists", name)
}
tp.components[name] = &tmpl{
Template: t,
m: tp.minifier,
}
}
}
// ParseComponent parses component from text
func (tp *Template) ParseComponent(name string, text string) {
tp.newComponent(name, func(t *template.Template) *template.Template {
return template.Must(t.New(name).Parse(text))
})
}
// ParseComponentFile loads component from file
func (tp *Template) ParseComponentFile(name string, filename string) {
tp.newComponent(name, func(t *template.Template) *template.Template {
if tp.fs == nil {
t = template.Must(t.ParseFiles(joinTemplateDir(tp.dir, filename)...))
} else {
t = template.Must(t.ParseFS(tp.fs, joinTemplateDir(tp.dir, filename)...))
}
t = t.Lookup(path.Base(filename))
return t
})
}
func (app *App) renderComponent(name string, args ...any) template.HTML {
t := app.component[name]
if t == nil {
panicf("component '%s' not found", name)
}
var d any
switch len(args) {
case 0:
case 1:
d = args[0]
default:
panicf("wrong number of data args for component '%s' want 0-1 got %d", name, len(args))
}
buf := getBytes()
defer putBytes(buf)
err := t.Execute(buf, d)
if err != nil {
panicf("component '%s' execute error: %v", name, err)
}
return template.HTML(buf.String())
}
func joinTemplateDir(dir string, filenames ...string) []string {
xs := make([]string, len(filenames))
for i, filename := range filenames {
xs[i] = path.Join(dir, filename)
}
return xs
}
func cloneTmpl(xs map[string]*tmpl) map[string]*tmpl {
if xs == nil {
return nil
}
rs := make(map[string]*tmpl)
for k, v := range xs {
rs[k] = v
}
return rs
}
func tfParam(name string, value any) *Param {
return &Param{Name: name, Value: value}
}