forked from AlecAivazis/survey
-
Notifications
You must be signed in to change notification settings - Fork 4
/
template.go
83 lines (70 loc) · 1.53 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
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
74
75
76
77
78
79
80
81
82
83
package core
import (
"bytes"
"text/template"
"github.com/mgutz/ansi"
)
var DisableColor = false
var (
HelpInputRune = '?'
ErrorIcon = "✘"
HelpIcon = "ⓘ"
QuestionIcon = "?"
MarkedOptionIcon = "◉"
UnmarkedOptionIcon = "◯"
SelectFocusIcon = "❯"
)
var TemplateFuncs = map[string]interface{}{
// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format
"color": func(color string) string {
if DisableColor {
return ""
}
return ansi.ColorCode(color)
},
"HelpInputRune": func() string {
return string(HelpInputRune)
},
"ErrorIcon": func() string {
return ErrorIcon
},
"HelpIcon": func() string {
return HelpIcon
},
"QuestionIcon": func() string {
return QuestionIcon
},
"MarkedOptionIcon": func() string {
return MarkedOptionIcon
},
"UnmarkedOptionIcon": func() string {
return UnmarkedOptionIcon
},
"SelectFocusIcon": func() string {
return SelectFocusIcon
},
}
var memoizedGetTemplate = map[string]*template.Template{}
func getTemplate(tmpl string) (*template.Template, error) {
if t, ok := memoizedGetTemplate[tmpl]; ok {
return t, nil
}
t, err := template.New("prompt").Funcs(TemplateFuncs).Parse(tmpl)
if err != nil {
return nil, err
}
memoizedGetTemplate[tmpl] = t
return t, nil
}
func RunTemplate(tmpl string, data interface{}) (string, error) {
t, err := getTemplate(tmpl)
if err != nil {
return "", err
}
buf := bytes.NewBufferString("")
err = t.Execute(buf, data)
if err != nil {
return "", err
}
return buf.String(), err
}