-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
template.go
39 lines (34 loc) · 926 Bytes
/
template.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
package template
import (
"bytes"
"fmt"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
)
func Compile(s string) (*template.Template, error) {
// delete some functions for security reason
fncs := sprig.TxtFuncMap()
delete(fncs, "env")
delete(fncs, "expandenv")
delete(fncs, "getHostByName")
return template.New("_").Funcs(fncs).Funcs(template.FuncMap{ //nolint:wrapcheck
"trimV": func(s string) string {
return strings.TrimPrefix(s, "v")
},
}).Parse(s)
}
func Execute(s string, input interface{}) (string, error) {
tpl, err := Compile(s)
if err != nil {
return "", fmt.Errorf("parse a template: %w", err)
}
return ExecuteTemplate(tpl, input)
}
func ExecuteTemplate(tpl *template.Template, input interface{}) (string, error) {
buf := &bytes.Buffer{}
if err := tpl.Execute(buf, input); err != nil {
return "", fmt.Errorf("render a template: %w", err)
}
return buf.String(), nil
}