forked from tkrajina/ftmpl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
73 lines (61 loc) · 1.85 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package ftmplting
import (
"strings"
texttmpl "text/template"
)
var generatorTemplate = texttmpl.Must(texttmpl.New("").Parse(`{{ .GlobalCode }}
// {{ .ErrFuncPrefix }}{{ .FuncName }} evaluates a template {{ .TemplateFile }}
func {{ .ErrFuncPrefix }}{{ .FuncName }}({{ .ArgsJoined }}) (string, error) {
_template := "{{ .TemplateFile }}"
_escape := {{ .EscapeFunc }}
var _ftmpl bytes.Buffer
_w := func(str string) { _, _ = _ftmpl.WriteString(str) }
_, _, _ = _template, _escape, _w
{{ range .Lines }}{{ . }}
{{ end }}
return _ftmpl.String(), nil
}
// {{ .NoerrFuncPrefix }}{{ .FuncName }} evaluates a template {{ .TemplateFile }}
func {{ .NoerrFuncPrefix }}{{ .FuncName }}({{ .ArgsJoined }}) string {
html, err := {{ .ErrFuncPrefix }}{{ .FuncName }}({{ .ArgNamesJoined }})
if err != nil {
_ ,_ = os.Stderr.WriteString("Error running template {{ .TemplateFile }}:" + err.Error())
}
return html
}`))
type templateParams struct {
GlobalCode string
ErrFuncPrefix string
NoerrFuncPrefix string
TemplateFile string
EscapeFunc string
FuncName string
Args []string
Lines []string
}
func (tp templateParams) ArgsJoined() string {
return strings.Join(tp.Args, ", ")
}
func (tp templateParams) ArgNamesJoined() string {
var argNames []string
for _, arg := range tp.Args {
argNames = append(argNames, strings.Split(arg, " ")[0])
}
return strings.Join(argNames, ", ")
}
var initFunctionTemplate = `func init() {
_ = fmt.Sprintf
_ = errors.New
_ = os.Stderr
_ = html.EscapeString
}`
var defaultQuoteTemplate = `func(str string) string {
return str
}`
var errorTemplate = texttmpl.Must(texttmpl.New("").Parse(`if {{.Expression}} {
return "", errors.New({{.Message}})
}`))
type errParams struct {
Expression, Message string
}
var stringTemplate = texttmpl.Must(texttmpl.New("").Parse(`_w(` + "`" + `{{ . }}` + "`" + `)`))