-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
52 lines (42 loc) · 1.08 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
package main
import (
"bytes"
"fmt"
"html/template"
"net/http"
)
var layoutFuncs = template.FuncMap{
"yield": func() (string, error) {
return "", fmt.Errorf("yield used incorrectly")
},
}
var layout = template.Must(
template.New("layout.html").Funcs(layoutFuncs).ParseFiles("templates/layout.html"),
)
var templates = template.Must(template.New("t").ParseGlob("templates/**/*.html"))
var errorTemplate = `
<html>
<body>
<h1>Error rendering template %s</h1>
<p>%s</p>
</body>
</html>
`
func RenderTemplate(w http.ResponseWriter, r *http.Request, templateName string, data map[string]interface{}) {
if data == nil {
data = map[string]interface{}{}
}
funcs := template.FuncMap{
"yield": func() (template.HTML, error) {
buf := bytes.NewBuffer(nil)
err := templates.ExecuteTemplate(buf, templateName, data)
return template.HTML(buf.String()), err
},
}
layoutClone, _ := layout.Clone()
layoutClone.Funcs(funcs)
err := layoutClone.Execute(w, data)
if err != nil {
http.Error(w, fmt.Sprintf(errorTemplate, templateName, err), http.StatusInternalServerError)
}
}