-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtemplate.go
102 lines (86 loc) · 2.3 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
package mail
import (
htmltmpl "html/template"
"io/fs"
"path/filepath"
"strings"
texttmpl "text/template"
"github.com/pkg/errors"
"github.com/samber/lo"
)
const (
extText = ".txt"
extHTML = ".gohtml"
)
type tmplCache struct {
text map[string]*texttmpl.Template
html map[string]*htmltmpl.Template
}
func newTmplCache() *tmplCache {
return &tmplCache{
text: make(map[string]*texttmpl.Template),
html: make(map[string]*htmltmpl.Template),
}
}
func (c *tmplCache) contains(name string) bool {
_, ok := c.text[name]
if ok {
return ok
}
_, ok = c.html[name]
return ok
}
func (c *tmplCache) getText(name string) (*texttmpl.Template, bool) {
tmpl, ok := c.text[name]
return tmpl, ok
}
func (c *tmplCache) getHTML(name string) (*htmltmpl.Template, bool) {
tmpl, ok := c.html[name]
return tmpl, ok
}
var templates *tmplCache
// ParseTemplates parses all templates in the given rootpath and stores them in the global templates cache.
//
// Must be called upon app initialization & before sending any messages.
func ParseTemplates(fsys fs.FS, rootpath string, baseTmplName ...string) error {
if templates == nil {
templates = newTmplCache()
}
rootpath = filepath.Clean(rootpath) + "/"
// TODO: support multiple base templates ?
hasBase := len(baseTmplName) > 0
baseTmpl := lo.Ternary(hasBase, baseTmplName[0], "")
paths, err := fs.Glob(fsys, rootpath+"*") // TODO: walk instead ?
if err != nil {
return errors.Wrapf(err, "globbing %s", rootpath)
}
for _, path := range paths {
filename := filepath.Base(path)
ext := filepath.Ext(filename)
isBase := lo.Ternary(hasBase, strings.HasPrefix(filename, baseTmpl), false)
if isBase || !(ext == extText || ext == extHTML) {
continue
}
name := filename[:strings.LastIndex(filename, ".")]
tmplPaths := lo.Ternary(
hasBase,
[]string{filepath.Join(rootpath, baseTmpl+ext), path},
[]string{path},
)
switch ext {
case extText:
tmpl, parseErr := texttmpl.ParseFS(fsys, tmplPaths...)
if parseErr != nil {
return errors.Wrapf(parseErr, "parsing %s files %v", ext, tmplPaths)
}
templates.text[name] = tmpl
case extHTML:
tmpl, parseErr := htmltmpl.ParseFS(fsys, tmplPaths...)
if parseErr != nil {
return errors.Wrapf(parseErr, "parsing %s files %v", ext, tmplPaths)
}
templates.html[name] = tmpl
}
}
return nil
}