-
Notifications
You must be signed in to change notification settings - Fork 8
/
template.go
115 lines (106 loc) · 2.54 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
package torgo
import (
"errors"
"fmt"
"html/template"
"os"
"path"
"path/filepath"
"strings"
)
var (
beegoTplFuncMap template.FuncMap
BeeTemplates map[string]*template.Template
BeeTemplateExt []string
)
func init() {
BeeTemplates = make(map[string]*template.Template)
beegoTplFuncMap = make(template.FuncMap)
BeeTemplateExt = make([]string, 0)
BeeTemplateExt = append(BeeTemplateExt, "tpl", "html")
beegoTplFuncMap["markdown"] = MarkDown
beegoTplFuncMap["dateformat"] = DateFormat
beegoTplFuncMap["date"] = Date
beegoTplFuncMap["compare"] = Compare
beegoTplFuncMap["substr"] = Substr
beegoTplFuncMap["html2str"] = Html2str
beegoTplFuncMap["str2html"] = Str2html
beegoTplFuncMap["htmlquote"] = Htmlquote
beegoTplFuncMap["htmlunquote"] = Htmlunquote
}
// AddFuncMap let user to register a func in the template
func AddFuncMap(key string, funname interface{}) error {
if _, ok := beegoTplFuncMap[key]; ok {
return errors.New("funcmap already has the key")
}
beegoTplFuncMap[key] = funname
return nil
}
type templatefile struct {
root string
files map[string][]string
}
func (self *templatefile) visit(paths string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
} else if (f.Mode() & os.ModeSymlink) > 0 {
return nil
} else {
hasExt := false
for _, v := range BeeTemplateExt {
if strings.HasSuffix(paths, v) {
hasExt = true
break
}
}
if hasExt {
replace := strings.NewReplacer("\\", "/")
a := []byte(paths)
a = a[len([]byte(self.root)):]
subdir := path.Dir(strings.TrimLeft(replace.Replace(string(a)), "/"))
if _, ok := self.files[subdir]; ok {
self.files[subdir] = append(self.files[subdir], paths)
} else {
m := make([]string, 1)
m[0] = paths
self.files[subdir] = m
}
}
}
return nil
}
func AddTemplateExt(ext string) {
for _, v := range BeeTemplateExt {
if v == ext {
return
}
}
BeeTemplateExt = append(BeeTemplateExt, ext)
}
func BuildTemplate(dir string) error {
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
return nil
} else {
return errors.New("dir open err")
}
}
self := templatefile{
root: dir,
files: make(map[string][]string),
}
err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
return self.visit(path, f, err)
})
if err != nil {
fmt.Printf("filepath.Walk() returned %v\n", err)
return err
}
for k, v := range self.files {
BeeTemplates[k] = template.Must(template.New("beegoTemplate" + k).Funcs(beegoTplFuncMap).ParseFiles(v...))
}
return nil
}