-
Notifications
You must be signed in to change notification settings - Fork 4
/
template.go
50 lines (41 loc) · 959 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"fmt"
"html/template"
"net/http"
"time"
"github.com/dustin/go-humanize"
)
func add(a, b int) int {
return a + b
}
func float64ToTime(v float64) time.Time {
return time.Unix(int64(v), 0)
}
func float64ToHuman(v float64) string {
return humanize.Time(float64ToTime(v))
}
var funcMap = template.FuncMap{
"add": add,
"float64ToTime": float64ToTime,
"float64ToHuman": float64ToHuman,
}
type appTemplate struct {
t *template.Template
}
func newAppTemplate(files ...string) *appTemplate {
base := template.Must(template.New("base").Funcs(funcMap).ParseFiles("base.html"))
template.Must(base.ParseFiles(files...))
return &appTemplate{base}
}
func (a appTemplate) Execute(w http.ResponseWriter, data interface{}) *AppError {
d := struct {
Data interface{}
}{
Data: data,
}
if err := a.t.Execute(w, d); err != nil {
return internalServerError(fmt.Errorf("execute template: %v", err))
}
return nil
}