-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplates.go
48 lines (41 loc) · 959 Bytes
/
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
package tpls
import (
"strings"
"text/template"
)
// Templates is used for templates rendering.
type Templates struct {
values map[string]interface{}
template *template.Template
}
type root struct {
Args map[string]interface{}
}
// New created template renderer with values to replace.
func New(values map[string]interface{}, funcMap template.FuncMap) *Templates {
t := &Templates{
values: values,
template: template.New("").Funcs(funcMap),
}
return t
}
// Validate verifies if template is correct.
func (t *Templates) Validate(s string) error {
_, err := t.template.Parse(s)
return err
}
// Render applies values and renders final output.
func (t *Templates) Render(s string) string {
sb := strings.Builder{}
template, err := t.template.Parse(s)
if err != nil {
//TODO: handle error
panic(err)
}
err = template.Execute(&sb, root{Args: t.values})
if err != nil {
//TODO: handle error
panic(err)
}
return sb.String()
}