-
Notifications
You must be signed in to change notification settings - Fork 42
/
multitemplate.go
97 lines (82 loc) · 2.29 KB
/
multitemplate.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
package multitemplate
import (
"fmt"
"html/template"
"io/fs"
"path/filepath"
"github.com/gin-gonic/gin/render"
)
// Render type
type Render map[string]*template.Template
var (
_ render.HTMLRender = Render{}
_ Renderer = Render{}
)
// New instance
func New() Render {
return make(Render)
}
// Add new template
func (r Render) Add(name string, tmpl *template.Template) {
if tmpl == nil {
panic("template can not be nil")
}
if len(name) == 0 {
panic("template name cannot be empty")
}
if _, ok := r[name]; ok {
panic(fmt.Sprintf("template %s already exists", name))
}
r[name] = tmpl
}
// AddFromFiles supply add template from files
func (r Render) AddFromFiles(name string, files ...string) *template.Template {
tmpl := template.Must(template.ParseFiles(files...))
r.Add(name, tmpl)
return tmpl
}
// AddFromGlob supply add template from global path
func (r Render) AddFromGlob(name, glob string) *template.Template {
tmpl := template.Must(template.ParseGlob(glob))
r.Add(name, tmpl)
return tmpl
}
// AddFromFS supply add template from fs.FS (e.g. embed.FS)
func (r Render) AddFromFS(name string, fsys fs.FS, files ...string) *template.Template {
tmpl := template.Must(template.ParseFS(fsys, files...))
r.Add(name, tmpl)
return tmpl
}
// AddFromString supply add template from strings
func (r Render) AddFromString(name, templateString string) *template.Template {
tmpl := template.Must(template.New(name).Parse(templateString))
r.Add(name, tmpl)
return tmpl
}
// AddFromStringsFuncs supply add template from strings
func (r Render) AddFromStringsFuncs(
name string,
funcMap template.FuncMap,
templateStrings ...string,
) *template.Template {
tmpl := template.New(name).Funcs(funcMap)
for _, ts := range templateStrings {
tmpl = template.Must(tmpl.Parse(ts))
}
r.Add(name, tmpl)
return tmpl
}
// AddFromFilesFuncs supply add template from file callback func
func (r Render) AddFromFilesFuncs(name string, funcMap template.FuncMap, files ...string) *template.Template {
tname := filepath.Base(files[0])
tmpl := template.Must(template.New(tname).Funcs(funcMap).ParseFiles(files...))
r.Add(name, tmpl)
return tmpl
}
// Instance supply render string
func (r Render) Instance(name string, data interface{}) render.Render {
return render.HTML{
Template: r[name],
Data: data,
}
}