-
Notifications
You must be signed in to change notification settings - Fork 0
/
text.go
45 lines (36 loc) · 857 Bytes
/
text.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
// Package text contains a layout based loader for text/template.
package text
import (
"fmt"
"io/fs"
"os"
"text/template"
"github.com/halimath/decor"
)
type fsLoader struct {
pattern string
fsys fs.FS
}
func NewFSLoader(templateNamePattern string, fsys fs.FS) decor.Loader {
return &fsLoader{
pattern: templateNamePattern,
fsys: fsys,
}
}
func NewFilesLoader(templateNamePattern, rootDir string) decor.Loader {
return NewFSLoader(templateNamePattern, os.DirFS(rootDir))
}
func (l *fsLoader) Load(names []string, funcs decor.FuncMap) (decor.Template, error) {
paths := make([]string, len(names))
for i, n := range names {
paths[i] = fmt.Sprintf(l.pattern, n)
}
t, err := template.ParseFS(l.fsys, paths...)
if err != nil {
return nil, err
}
if funcs != nil {
t = t.Funcs(template.FuncMap(funcs))
}
return t, nil
}