-
Notifications
You must be signed in to change notification settings - Fork 1
/
funcs.go
49 lines (43 loc) · 1.34 KB
/
funcs.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
package changeset
import (
"strings"
"github.com/canopyclimate/golive/htmltmpl"
)
// Funcs returns a map of functions that can be used in templates:
// - inputTag: renders an input tag with the given key and value for the provided changeset
// - errorTag: renders an error tag if there is an error for the given key in the provided changeset
func Funcs() htmltmpl.FuncMap {
return htmltmpl.FuncMap{
"inputTag": InputTag,
"errorTag": ErrorTag,
}
}
var (
inputTagTmpl = htmltmpl.Must(htmltmpl.New("inputTag").Parse(
`<input type="text" name="{{ .Key }}" value="{{ .Val }}"/>`,
))
errorTagTmpl = htmltmpl.Must(htmltmpl.New("errorTag").Parse(
`<span class="error">{{ . }}</span>`,
))
)
// InputTag renders an input tag with the given key and value for the provided changeset.
func InputTag(cs Any, key string) htmltmpl.HTML {
val := cs.Value(key)
buf := new(strings.Builder)
dot := struct{ Key, Val string }{Key: key, Val: val}
err := inputTagTmpl.Execute(buf, dot)
if err != nil {
panic(err)
}
return htmltmpl.HTML(buf.String())
}
// ErrorTag renders an error tag if there is an error for the given key in the provided changeset.
func ErrorTag(cs Any, key string) htmltmpl.HTML {
val := cs.Error(key)
buf := new(strings.Builder)
err := errorTagTmpl.Execute(buf, val)
if err != nil {
panic(err)
}
return htmltmpl.HTML(buf.String())
}