-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.go
More file actions
302 lines (257 loc) · 6.7 KB
/
template.go
File metadata and controls
302 lines (257 loc) · 6.7 KB
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package template
import (
"bytes"
"fmt"
"html/template"
"io"
"os"
"regexp"
"sync"
"github.com/go-universal/fs"
)
// Template defines the interface for template operations.
type Template interface {
// Load loads shared templates from the filesystem.
Load() error
// Exists checks if a template exists.
Exists(name string) (bool, error)
// Render renders a template to the provided writer with
// the given view, data, and optional layouts.
Render(w io.Writer, view string, data interface{}, layouts ...string) error
// Compile compiles a template with the given name, layout, and data.
Compile(name, layout string, data any, partials ...string) ([]byte, error)
}
type tplEngine struct {
option option
fs fs.FlexibleFS
base *template.Template
templates map[string]*template.Template
partialRx *regexp.Regexp
mutex sync.RWMutex
}
// New creates a new Template instance with the provided filesystem and options.
func New(fs fs.FlexibleFS, options ...Options) Template {
// Initialize default options
option := &option{
root: ".",
partials: "",
extension: ".tpl",
leftDelim: "{{",
rightDelim: "}}",
Dev: false,
Cache: false,
Pipes: make(template.FuncMap),
}
for _, opt := range options {
opt(option)
}
// Create and return the template engine
return &tplEngine{
option: *option,
fs: fs,
}
}
func (t *tplEngine) Load() error {
var err error
// Safe race condition
t.mutex.Lock()
defer t.mutex.Unlock()
// Initialize
t.templates = make(map[string]*template.Template)
t.base = template.New("").
Delims(t.option.leftDelim, t.option.rightDelim).
Funcs(t.option.Pipes)
// Add built-in pipes
viewPipe(t.base, nil)
existsPipe(t.base)
includePipe(t.base)
requirePipe(t.base)
// Generate partial pattern
if t.option.partials != "" {
t.partialRx, err = regexp.Compile(extPattern(
t.option.partials,
t.option.extension,
))
if err != nil {
return err
}
}
// Read files from fs
files, err := t.fs.Lookup(
t.option.root,
extPattern("", t.option.extension),
)
if err != nil {
return err
}
// Load partials
if t.option.partials != "" {
for _, file := range files {
// Skip non partials
if !t.partialRx.MatchString(file) {
continue
}
// Generate friendly name
name := toName(file, t.option.partials, t.option.extension)
name = "@partials/" + name
// Read file
content, err := t.fs.ReadFile(file)
if err != nil {
return err
}
_, err = t.base.New(name).Parse(string(content))
if err != nil {
return err
}
}
}
return nil
}
func (t *tplEngine) Exists(name string) (bool, error) {
// Reload on development mode
if t.option.Dev {
if err := t.Load(); err != nil {
return false, err
}
}
// Resolve and normalize view
view := toPath(name, t.option.root, t.option.extension)
viewId := toName(view, t.option.root, t.option.extension)
key := toKey(viewId)
// Safe race condition
t.mutex.RLock()
defer t.mutex.RUnlock()
// Check if template exists in rendered templates
if _, ok := t.templates[key]; ok {
return true, nil
}
// Check if template exists in the filesystem
if _, err := t.fs.ReadFile(view); os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
func (t *tplEngine) Render(w io.Writer, name string, data interface{}, layouts ...string) error {
var err error
// Reload on development mode
if t.option.Dev {
if err := t.Load(); err != nil {
return err
}
}
// Resolve and normalize view
view := toPath(name, t.option.root, t.option.extension)
viewId := toName(view, t.option.root, t.option.extension)
// Resolve and normalize layout and partials
layout := ""
layoutId := ""
partials := make([]string, 0)
partialsId := make([]string, 0)
if len(layouts) > 0 {
for i := range layouts {
if i == 0 {
layout = toPath(layouts[0], t.option.root, t.option.extension)
layoutId = toName(layout, t.option.root, t.option.extension)
} else if layouts[i] != "" {
name := toPath(layouts[i], t.option.root, t.option.extension)
id := toName(name, t.option.root, t.option.extension)
partials = append(partials, name)
partialsId = append(partialsId, id)
}
}
}
// Generate key
key := toKey(append([]string{viewId, layoutId}, partialsId...)...)
// Check partials render
if t.partialRx != nil && t.partialRx.MatchString(view) {
return fmt.Errorf("%s partial cannot render directly", view)
}
if layout != "" && t.partialRx != nil && t.partialRx.MatchString(layout) {
return fmt.Errorf("%s partial cannot render directly", layout)
}
for _, partial := range partials {
if t.partialRx != nil && t.partialRx.MatchString(partial) {
return fmt.Errorf("%s partial already loaded globally", layout)
}
}
// Safe race condition
t.mutex.RLock()
defer t.mutex.RUnlock()
// Resolve Template
tpl, ok := t.templates[key]
if !ok {
// Clone from base engine
tpl, err = t.base.Clone()
if err != nil {
return err
}
// Read and parse view
if raw, err := t.fs.ReadFile(view); os.IsNotExist(err) {
return fmt.Errorf("%s template not found", view)
} else if err != nil {
return err
} else {
_, err := tpl.New("view::" + viewId).Parse(string(raw))
if err != nil {
return err
}
}
// Read and parse layout
if layout != "" {
if raw, err := t.fs.ReadFile(layout); os.IsNotExist(err) {
return fmt.Errorf("%s layout template not found", layout)
} else if err != nil {
return err
} else {
_, err := tpl.New("layout::" + layoutId).Parse(string(raw))
if err != nil {
return err
}
}
}
for i := range partials {
if raw, err := t.fs.ReadFile(partials[i]); os.IsNotExist(err) {
return fmt.Errorf("%s partial template not found", partials[i])
} else if err != nil {
return err
} else {
_, err := tpl.New(partialsId[i]).Parse(string(raw))
if err != nil {
return err
}
}
}
// Store to cache
if !t.option.Dev && t.option.Cache {
t.templates[key] = tpl
}
}
// Add built-in pipes
viewPipe(tpl, nil)
existsPipe(tpl)
includePipe(tpl)
requirePipe(tpl)
// Render
if layout == "" {
return tpl.ExecuteTemplate(w, "view::"+viewId, underlyingValue(data))
} else {
// Render child view to layout
var buf bytes.Buffer
err = tpl.ExecuteTemplate(&buf, "view::"+viewId, underlyingValue(data))
if err != nil {
return err
}
viewPipe(tpl, buf.Bytes())
return tpl.ExecuteTemplate(w, "layout::"+layoutId, underlyingValue(data))
}
}
func (t *tplEngine) Compile(name, layout string, data any, partials ...string) ([]byte, error) {
var buf bytes.Buffer
err := t.Render(&buf, name, data, append([]string{layout}, partials...)...)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}