-
Notifications
You must be signed in to change notification settings - Fork 5
/
templates.go
82 lines (75 loc) · 1.48 KB
/
templates.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
package sgo
import (
"fmt"
"html/template"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
)
// Templates is a templates manager.
type Templates struct {
Dir string
Suffix string
template *template.Template
FuncMap template.FuncMap
}
// NewTemplates .
func NewTemplates(tplDir string, funcMap template.FuncMap) *Templates {
tpl := &Templates{
Dir: tplDir,
Suffix: ".html",
FuncMap: funcMap,
}
tpl.loadTpls()
return tpl
}
// Render Templates.
func (tpl *Templates) Render(w io.Writer, tplname string, data interface{}) error {
return tpl.template.ExecuteTemplate(w, tplname, data)
}
func (tpl *Templates) loadTpls() {
tpl.template = template.New("_SGo_").
Funcs(tpl.FuncMap)
tpls, err := tpl.walkDir()
if err != nil {
fmt.Println(err)
os.Exit(3)
}
for _, t := range tpls {
tpl.parseFile(t)
}
}
func (tpl *Templates) walkDir() ([]string, error) {
files := make([]string, 0)
err := filepath.Walk(tpl.Dir, func(filename string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
files = append(files, filename[len(tpl.Dir)+1:])
return nil
})
if err != nil {
return nil, err
}
return files, nil
}
func (tpl *Templates) parseFile(filename string) error {
b, err := ioutil.ReadFile(path.Join(tpl.Dir, filename))
if err != nil {
return err
}
t := tpl.template.Lookup(filename)
if t == nil {
t = tpl.template.New(filename)
}
t, err = t.Parse(string(b))
if err != nil {
return err
}
return nil
}