-
Notifications
You must be signed in to change notification settings - Fork 0
/
tempest.go
230 lines (202 loc) · 5.41 KB
/
tempest.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Copyright (c) 2022 Noel Ukwa. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be found
// in the LICENSE file.
// Package tempest is a simple template grouping helper for GO.
//
// It is intended to be used in conjuction with go html/template package,
// and not a replacement for the html/template package.
//
// A simple example:
//
// package main
//
// import (
// "fmt"
// "html/template"
// "log"
// "net/http"
// "os"
//
// "github.com/noelukwa/tempest"
// )
//
// //go:embed views
// var views embed.FS
//
// func main() {
// t := tempest.New()
//
// templates, err := t.LoadFS(os.DirFS("views"))
// if err != nil {
// log.Fatal(err)
// }
//
// http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// err := templates["index"].Execute(w, nil)
// if err != nil {
// log.Fatal(err)
// }
// })
//
// http.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
// err := templates["admin/index"].Execute(w, nil)
// if err != nil {
// log.Fatal(err)
// }
// })
//
// fmt.Println("Listening on port 8080")
// log.Fatal(http.ListenAndServe(":8080", nil))
// }
//
// The above example will load all the templates in the views directory and
// subdirectories, and will group them into a map of templates to filenames.
//
package tempest
import (
"fmt"
"html/template"
"io/fs"
"path/filepath"
"sort"
"strings"
)
// Config is the configuration for the tempest instance.
// It is used to set the file extension, the directory where the includes are
// stored, and the name used for layout templates.
// Defaults are set for each of these fields if tempest is initialized
// without a config.
type Config struct {
// The file extension of the templates.
// Defaults to ".html".
Ext string
// The directory where the includes are stored.
// Defaults to "includes".
IncludesDir string
// The name used for layout templates :- templates that wrap other contents.
// Defaults to "layout.html".
Layout string
}
type tempest struct {
temps map[string]*template.Template
conf *Config
}
// New returns a new tempest instance with default configuration.
func New() *tempest {
return &tempest{
temps: make(map[string]*template.Template),
conf: &Config{
Ext: ".html",
IncludesDir: "includes",
Layout: "layout",
},
}
}
// WithConfig sets the configuration for the tempest instance.
func WithConfig(conf *Config) *tempest {
if conf.Ext == "" {
conf.Ext = ".html"
}
if conf.IncludesDir == "" {
conf.IncludesDir = "includes"
}
if conf.Layout == "" {
conf.Layout = "layout"
}
return &tempest{
temps: make(map[string]*template.Template),
conf: conf,
}
}
// LoadFS loads templates from an embedded filesystem and returns a map of
// templates to filenames.
func (tempest *tempest) LoadFS(files fs.FS) (map[string]*template.Template, error) {
includesDir := filepath.Clean(tempest.conf.IncludesDir)
layoutFile := filepath.Clean(tempest.conf.Layout + tempest.conf.Ext)
includes := make([]string, 0)
layouts := make([]string, 0)
rawTemps := make(map[string]string)
templates := make(map[string]*template.Template)
// Walk through the files and load them into the map
err := fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if filepath.Base(path) == includesDir {
includes = append(includes, path)
return fs.SkipDir
}
}
if !d.IsDir() {
if filepath.Ext(path) == tempest.conf.Ext {
if filepath.Base(path) != layoutFile {
rawTemps[path] = path
} else {
layouts = append(layouts, path)
}
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("error walking directory: %w", err)
}
// sort the includes
sort.Slice(includes, func(i, j int) bool {
return len(includes[i]) < len(includes[j])
})
// sort the layouts
sort.Slice(layouts, func(i, j int) bool {
return len(layouts[i]) < len(layouts[j])
})
for _, t := range rawTemps {
// get the layouts
lyts := getLayouts(t, layouts)
lyts = append(lyts, t)
// get the name of the template
name := filepath.Base(lyts[0])
temp := template.New(name)
// get the includes
incls := getIncludes(t, includes)
for _, i := range incls {
xfiles, err := fs.Glob(files, fmt.Sprintf("%s/*%s", i, tempest.conf.Ext))
if err != nil {
return nil, fmt.Errorf("error getting includes: %w", err)
}
temp, err = temp.ParseFS(files, xfiles...)
if err != nil {
return nil, fmt.Errorf("error parsing includes: %w", err)
}
}
// parse the layout files
temp, err = temp.ParseFS(files, lyts...)
if err != nil {
return nil, fmt.Errorf("error parsing layouts: %w", err)
}
// remove the extension from the template name
// views/admin/index.html -> admin/index
key := strings.TrimPrefix(t, strings.Split(t, "/")[0]+"/")
key = strings.TrimSuffix(key, filepath.Ext(key))
templates[key] = temp
}
return templates, nil
}
func getIncludes(path string, includes []string) []string {
inc := make([]string, 0)
for _, i := range includes {
if strings.HasPrefix(path, filepath.Dir(i)) || filepath.Dir(i) == "." {
inc = append(inc, i)
}
}
return inc
}
func getLayouts(path string, layouts []string) []string {
lay := make([]string, 0)
for _, l := range layouts {
if strings.HasPrefix(path, filepath.ToSlash(filepath.Dir(l))) || filepath.Dir(l) == "." {
lay = append(lay, l)
}
}
return lay
}