/
render.go
92 lines (83 loc) · 1.79 KB
/
render.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
package gtemplate
import (
"errors"
ghash "github.com/snail007/gmc/util/hash"
"sync"
)
var DefaultRender = NewRender()
type Render struct {
tplCache map[string]*Template
tplLock sync.Mutex
funcMap map[string]interface{}
leftDelims,
rightDelims string
}
func NewRender() *Render {
return &Render{
tplCache: map[string]*Template{},
funcMap: map[string]interface{}{},
}
}
func (s *Render) clearTemplateCache() {
s.tplLock.Lock()
defer s.tplLock.Unlock()
s.tplCache = map[string]*Template{}
}
func (s *Render) Delims(left, right string) *Render {
s.clearTemplateCache()
s.leftDelims = left
s.rightDelims = right
return s
}
func (s *Render) AddFuncMap(m map[string]interface{}) *Render {
if len(m) == 0 {
return s
}
s.clearTemplateCache()
for k, v := range m {
s.funcMap[k] = v
}
return s
}
func (s *Render) getTemplate(tplBytes []byte) (*Template, error) {
s.tplLock.Lock()
defer s.tplLock.Unlock()
id := ghash.Md5Bytes(tplBytes)
if t, ok := s.tplCache[id]; ok {
return t, nil
}
t := New()
t.SetCtx(ctx)
t.DdisableLogging()
t.DisableLoadDefaultBinData()
t.SetBinBytes(map[string][]byte{"tpl": tplBytes})
if s.leftDelims != "" && s.rightDelims != "" {
t.Delims(s.leftDelims, s.rightDelims)
}
if len(s.funcMap) > 0 {
t.Funcs(s.funcMap)
}
err := t.Parse()
if err != nil {
return nil, err
}
s.tplCache[id] = t
return t, nil
}
// Parse the template, tplBytesOrString is []byte or string template
func (s *Render) Parse(tplBytesOrString interface{}, tplData map[string]interface{}) (d []byte, err error) {
var b []byte
switch v := tplBytesOrString.(type) {
case []byte:
b = v
case string:
b = []byte(v)
default:
return nil, errors.New("wrong type of tpl data")
}
t, err := s.getTemplate(b)
if err != nil {
return
}
return t.Execute("tpl", tplData)
}