-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtpl.go
55 lines (44 loc) · 1.09 KB
/
tpl.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
package goherence
import (
"fmt"
"html/template"
"io"
"net/http"
)
var TemplateFuncs template.FuncMap
func init() {
TemplateFuncs = template.FuncMap{
"attrs": func(e Partial) template.HTMLAttr {
return template.HTMLAttr(
fmt.Sprintf(
`data-id="%s" data-href="/%s" data-ts="%d"`, e.ID(), e.ID(), millis(e.Timestamp())))
},
"millis": millis,
}
}
type TemplateData struct {
Partial
Value interface{}
}
func writerToHandler(wt io.WriterTo) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := wt.WriteTo(w)
if err != nil {
http.Error(w, err.Error(), 500)
}
})
}
type RenderFunc func(interface{}, Partial) io.WriterTo
func TemplateRenderFunc(tpl *template.Template, name string) RenderFunc {
return func(v interface{}, p Partial) io.WriterTo {
return writerToFunc(func(w io.Writer) (int64, error) {
fmt.Printf("rendering %s with template %s with value %v\n", p.ID(), name, v)
cw := &countWriter{w: w}
err := tpl.ExecuteTemplate(cw, name, TemplateData{
Partial: p,
Value: v,
})
return cw.n, err
})
}
}