-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
48 lines (42 loc) · 1 KB
/
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
40
41
42
43
44
45
46
47
48
package entity
import (
"bytes"
"text/template"
"golang.org/x/xerrors"
)
var (
TemplateFnsMap = map[string]any{
"random": func() any { return RandomFn{} },
"slice": func() any { return SLiceFn{} },
}
)
type TmplProc struct {
templateData map[string]any
templateFns map[string]any
templateOptions []string
}
func NewTemplateProc(
templateData,
templateFns map[string]any,
templateOptions []string) *TmplProc {
return &TmplProc{
templateData: templateData,
templateFns: templateFns,
templateOptions: templateOptions,
}
}
func (p *TmplProc) Process(name, text string) (string, error) {
tmpl, err := template.New(name).
Funcs(p.templateFns).
Option(p.templateOptions...).
Parse(text)
if err != nil {
return Empty, xerrors.Errorf("process template: new template [%s]: %w", name, err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, p.templateData)
if err != nil {
return Empty, xerrors.Errorf("process template: execute [%s]: %w", name, err)
}
return buf.String(), err
}