-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtemplate.go
33 lines (27 loc) · 894 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
package sqltmpl
import (
"bytes"
"strings"
"text/template"
)
// Template is the representation of a parsed template.
type Template struct {
tpl *template.Template
placeholderFunc func(i int) string
}
func New(tpl *template.Template, placeholderFunc func(i int) string) *Template {
return &Template{
tpl: tpl,
placeholderFunc: placeholderFunc,
}
}
// Execute executes a template by the specified name and pass the specified data to the template Context
// then it returns the (SQL statement, the bindings) or any error if any.
func (t *Template) Execute(name string, data any) (string, []any, error) {
output := bytes.NewBuffer(nil)
ctx := Context{Args: data, placeholderFunc: t.placeholderFunc}
if err := t.tpl.ExecuteTemplate(output, name, &ctx); err != nil {
return "", nil, err
}
return strings.TrimSpace(output.String()), ctx.bindings, nil
}