-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
104 lines (83 loc) · 1.81 KB
/
templates.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
package main
import (
"embed"
"html/template"
"io/fs"
"path/filepath"
)
type kvTable struct {
Title string
Values map[string]string
}
type templateData struct {
KvTables map[string]*kvTable
}
//go:embed templates/*.tmpl
var templates embed.FS
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
pageCache := map[string]string{}
layoutCache := map[string]string{}
partialCache := map[string]string{}
err := fs.WalkDir(templates, "templates", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
name := filepath.Base(path)
if ok, err := filepath.Match("*.page.tmpl", name); ok || err != nil {
if err != nil {
return err
}
file, err := fs.ReadFile(templates, path)
if err != nil {
return err
}
pageCache[name] = string(file)
} else if ok, err := filepath.Match("*.layout.tmpl", name); ok || err != nil {
if err != nil {
return err
}
file, err := fs.ReadFile(templates, path)
if err != nil {
return err
}
layoutCache[name] = string(file)
} else if ok, err := filepath.Match("*.partial.tmpl", name); ok || err != nil {
if err != nil {
return err
}
file, err := fs.ReadFile(templates, path)
if err != nil {
return err
}
partialCache[name] = string(file)
}
return nil
})
if err != nil {
return nil, err
}
for name, file1 := range pageCache {
ts, err := template.New(name).Parse(file1)
if err != nil {
return nil, err
}
for _, file2 := range layoutCache {
ts, err = ts.Parse(file2)
if err != nil {
return nil, err
}
}
for _, file3 := range partialCache {
ts, err = ts.Parse(file3)
if err != nil {
return nil, err
}
}
cache[name] = ts
}
return cache, nil
}