forked from muety/wakapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
63 lines (51 loc) · 1.09 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
package utils
import (
"encoding/json"
"html/template"
"io"
"io/fs"
"path"
)
type TemplateMap map[string]*template.Template
func Json(data interface{}) template.JS {
d, err := json.Marshal(data)
if err != nil {
return ""
}
return template.JS(d)
}
func ToRunes(s string) (r []string) {
for _, c := range []rune(s) {
r = append(r, string(c))
}
return r
}
func LoadTemplates(templateFs fs.FS, funcs template.FuncMap) (TemplateMap, error) {
tpls := template.New("").Funcs(funcs)
templates := make(map[string]*template.Template)
files, err := fs.ReadDir(templateFs, ".")
if err != nil {
return nil, err
}
for _, file := range files {
tplName := file.Name()
if file.IsDir() || path.Ext(tplName) != ".html" {
continue
}
templateFile, err := templateFs.Open(tplName)
if err != nil {
return nil, err
}
templateData, err := io.ReadAll(templateFile)
if err != nil {
return nil, err
}
templateFile.Close()
tpl, err := tpls.New(tplName).Parse(string(templateData))
if err != nil {
return nil, err
}
templates[tplName] = tpl
}
return templates, nil
}