-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
69 lines (59 loc) · 1.21 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
// static.v2
// Copyright (c) 2020, HuguesGuilleus
// BSD 3-Clause License
package static
import (
"errors"
"io"
"os"
"path/filepath"
"text/template"
)
var templateNoInit = errors.New("The template is not init.")
// Can be breaken
type Template struct {
T *template.Template
get func() []byte
}
func NewTemplate() *Template {
return &Template{}
}
func (t *Template) Execute(w io.Writer, data interface{}) error {
if t == nil || t.T == nil {
return templateNoInit
}
if Dev && t.get != nil {
t.parse(t.get())
}
return t.T.Execute(w, data)
}
func (t *Template) Bytes(in []byte) *Template {
t.get = nil
if Dev {
t.parse(in)
} else {
t.parse(HtmlMinify(in))
}
return t
}
func (t *Template) Func(f func() []byte) *Template {
t.get = f
t.parse(HtmlMinify(f()))
return t
}
func (t *Template) File(f string) *Template {
t.get = func() []byte { return readFileOnce(os.DirFS(f), HtmlMinify) }
t.parse(t.get())
return t
}
func (t *Template) FileJoinPath(path ...string) *Template {
return t.File(filepath.Join(path...))
}
func (t *Template) parse(in []byte) {
var err error
t.T, err = template.New("").Parse(string(in))
if err != nil {
t.T = nil
Log.Printf("template parse error: %v", err)
}
}