-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodel.go
69 lines (59 loc) · 1.61 KB
/
model.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
package template
import (
"errors"
"fmt"
"html/template"
"io"
"io/fs"
"path/filepath"
)
// H is a shortcut for map[string]interface{}
type H map[string]interface{}
// FuncMap ...
type FuncMap template.FuncMap
// NewFuncMap instance
func NewFuncMap() FuncMap {
return make(FuncMap)
}
// Render type
type Render map[string]*template.Template
// NewRender instance
func NewRender() Render {
return make(Render)
}
// Add new template
func (r Render) Add(name string, tmpl *template.Template) error {
if tmpl == nil {
return errors.New("template can not be nil")
}
if len(name) == 0 {
return errors.New("template name cannot be empty")
}
if _, ok := r[name]; ok {
return fmt.Errorf("template %s already exists", name)
}
r[name] = tmpl
return nil
}
// AddFromFilesFuncs supply add template from file callback func
func (r Render) AddFromFilesFuncs(name string, funcMap FuncMap, files ...string) *template.Template {
tname := filepath.Base(files[0])
tmpl := template.Must(template.New(tname).Funcs(template.FuncMap(funcMap)).ParseFiles(files...))
r.Add(name, tmpl)
return tmpl
}
// AddFromFSFuncs supply add template from fs callback func
func (r Render) AddFromFSFuncs(name string, funcMap FuncMap, fs fs.FS, files ...string) *template.Template {
tname := filepath.Base(files[0])
tmpl := template.Must(template.New(tname).Funcs(template.FuncMap(funcMap)).ParseFS(fs, files...))
r.Add(name, tmpl)
return tmpl
}
// Execute 执行
func (r Render) Execute(name string, wr io.Writer, data interface{}) error {
t, ok := r[name]
if !ok {
return fmt.Errorf("template %s not exists", name)
}
return t.Execute(wr, data)
}