-
Notifications
You must be signed in to change notification settings - Fork 52
/
templates.go
62 lines (54 loc) · 1.33 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
package templates
import (
"bytes"
"embed"
"fmt"
"io/fs"
"path/filepath"
"strings"
"text/template"
)
var (
//go:embed templates/*
content embed.FS
templates map[string]string
)
func init() {
dirPath := "templates"
dirEntries, err := fs.ReadDir(content, dirPath)
if err != nil {
panic(fmt.Errorf("unable to load templates: %w", err))
}
templates = make(map[string]string, len(dirEntries))
for _, entry := range dirEntries {
if entry.IsDir() {
continue
}
filePath := filepath.Join(dirPath, entry.Name())
file, err := fs.ReadFile(content, filePath)
if err != nil {
panic(fmt.Errorf("unable to load template '%s': %w", filePath, err))
}
templates[entry.Name()] = string(file)
}
}
func LoadAndExecute(templateName string, funcMap template.FuncMap, data interface{}) (str string, err error) {
var tplFunctions = template.FuncMap{
"UpperCase": strings.ToUpper,
"LowerCase": strings.ToLower,
"ListAsString": func(elems []string) string { return strings.Join(elems, ",") },
}
for key, value := range funcMap {
tplFunctions[key] = value
}
tplStr := templates[templateName]
tpl, err := template.New(templateName).Funcs(tplFunctions).Parse(tplStr)
if err != nil {
return
}
buffIspn := new(bytes.Buffer)
if err = tpl.Execute(buffIspn, data); err != nil {
return
}
return buffIspn.String(), nil
}