/
ginpon.go
55 lines (42 loc) · 1.03 KB
/
ginpon.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 ginpon
import (
"net/http"
"path"
"github.com/flosch/pongo2"
"github.com/gin-gonic/gin/render"
)
type (
Pongo2Common struct {
BasePath string
}
Pongo2 struct {
Template *pongo2.Template
Name string
Data interface{}
}
Context pongo2.Context
)
var htmlContentType = []string{"text/html; charset=utf-8"}
func New(path string, isDebug bool) *Pongo2Common {
pongo2.DefaultSet.Debug = isDebug
return &Pongo2Common{BasePath: path}
}
func (p Pongo2Common) Instance(name string, data interface{}) render.Render {
tpl := pongo2.Must(pongo2.FromCache(path.Join(p.BasePath, name)))
return &Pongo2{
Template: tpl,
Name: name,
Data: data,
}
}
func (p Pongo2) Render(w http.ResponseWriter) error {
p.writeContentType(w, htmlContentType)
c := pongo2.Context(p.Data.(Context))
return p.Template.ExecuteWriter(c, w)
}
func (p Pongo2) writeContentType(w http.ResponseWriter, value []string) {
header := w.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = value
}
}