-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
71 lines (60 loc) · 1.54 KB
/
render.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"text/template"
"github.com/Masterminds/sprig/v3"
)
func loadTmplData() map[string]any {
ret := map[string]any{}
data, err := os.ReadFile(config)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(data, &ret)
if err != nil {
log.Fatal(err)
}
return ret
}
// loadFile reads the file and attempt to render it as a template, returns
// the original file, the rendered. In case of errors the returned value
// will contain the error text.
func loadFile(fpath string, tdata map[string]any) (string, string, error) {
fdata, err := os.ReadFile(fpath)
if err != nil {
return fmt.Sprintf("error reading file %s: %+v\n", fpath, err), "", nil
}
t := template.New(fpath).Option("missingkey=zero").Funcs(sprig.FuncMap())
setDelimiters(t, tdata)
fstring := string(fdata)
t, err = t.Parse(fstring)
if err != nil {
return fstring, fmt.Sprintf("error parsing template %s: %+v\n", fpath, err), err
}
var buff bytes.Buffer
err = t.Execute(&buff, tdata)
if err != nil {
return fstring, fmt.Sprintf("error rendering template %s: %+v\n", fpath, err), err
}
return fstring, buff.String(), nil
}
const (
leftDelim = "left_delimiter"
rightDelim = "right_delimiter"
)
// finds and sets the delimiters
func setDelimiters(t *template.Template, tdata map[string]any) {
// default delimiters, left and right
var ld, rd = "{{", "}}"
if left, ok := tdata[leftDelim]; ok {
ld = left.(string)
}
if right, ok := tdata[rightDelim]; ok {
rd = right.(string)
}
t.Delims(ld, rd)
}