/
render.go
77 lines (63 loc) · 1.46 KB
/
render.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
package render
import (
"bytes"
"html/template"
"io"
"net/http"
"github.com/gin-gonic/gin"
)
const (
ContentType = "Content-Type"
ContentHTML = "text/html; charset=UTF-8"
)
var templates *template.Template
type Renderer struct {
http.ResponseWriter
req *http.Request
}
func init() {
loadTemplates()
}
func loadTemplates() {
templates = template.New("templates")
funcs := template.FuncMap{
"yield": func() (template.HTML, error) {
return "", nil
},
}
template.Must(templates.Funcs(funcs).ParseGlob("templates/*"))
}
func New(context *gin.Context) *Renderer {
if gin.IsDebugging() {
loadTemplates()
}
return &Renderer{
ResponseWriter: context.Writer,
req: context.Request,
}
}
func (r *Renderer) HTML(status int, name string, binding interface{}) {
addYield(name, binding)
out, err := execute("layout.tmpl", binding)
if err != nil {
http.Error(r, err.Error(), http.StatusInternalServerError)
return
}
// template rendered fine, write out the result
r.Header().Set(ContentType, ContentHTML)
r.WriteHeader(status)
io.Copy(r, out)
}
func execute(name string, binding interface{}) (*bytes.Buffer, error) {
buf := new(bytes.Buffer)
return buf, templates.ExecuteTemplate(buf, name, binding)
}
func addYield(name string, binding interface{}) {
funcs := template.FuncMap{
"yield": func() (template.HTML, error) {
buf, err := execute(name, binding)
return template.HTML(buf.String()), err
},
}
templates.Funcs(funcs)
}