-
Notifications
You must be signed in to change notification settings - Fork 23
/
view.go
92 lines (84 loc) · 1.97 KB
/
view.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 GoInk
import (
"bytes"
"html/template"
"os"
"path"
"strings"
)
// View instance provides simple template render.
type View struct {
// template directory
Dir string
// view functions map
FuncMap template.FuncMap
// Cache Flag
IsCache bool
// template cache map
templateCache map[string]*template.Template
}
func (v *View) getTemplateInstance(tpl []string) (*template.Template, error) {
key := strings.Join(tpl, "-")
// if IsCache, get cached template if exist
if v.IsCache {
if v.templateCache[key] != nil {
return v.templateCache[key], nil
}
}
var (
t *template.Template
e error
file []string = make([]string, len(tpl))
)
for i, tp := range tpl {
file[i] = path.Join(v.Dir, tp)
}
t = template.New(path.Base(tpl[0]))
t.Funcs(v.FuncMap)
t, e = t.ParseFiles(file...)
if e != nil {
return nil, e
}
if v.IsCache {
v.templateCache[key] = t
}
return t, nil
}
// Render renders template with data.
// Tpl is the file names under template directory, like tpl1,tpl2,tpl3.
func (v *View) Render(tpl string, data map[string]interface{}) ([]byte, error) {
t, e := v.getTemplateInstance(strings.Split(tpl, ","))
if e != nil {
return nil, e
}
var buf bytes.Buffer
e = t.Execute(&buf, data)
if e != nil {
return nil, e
}
return buf.Bytes(), nil
}
// Has checks the template file existing.
func (v *View) Has(tpl string) bool {
f := path.Join(v.Dir, tpl)
_, e := os.Stat(f)
return e == nil
}
// NoCache sets view cache off and clean cached data.
func (v *View) NoCache(){
v.IsCache = false
v.templateCache = make(map[string]*template.Template)
}
// NewView returns view instance with directory.
// It contains bundle template function HTML(convert string to template.HTML).
func NewView(dir string) *View {
v := new(View)
v.Dir = dir
v.FuncMap = make(template.FuncMap)
v.FuncMap["Html"] = func(str string) template.HTML {
return template.HTML(str)
}
v.IsCache = false
v.templateCache = make(map[string]*template.Template)
return v
}