forked from ngerakines/ginpongo2
/
middleware.go
36 lines (31 loc) · 871 Bytes
/
middleware.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
package ginpongo2
import (
"github.com/flosch/pongo2"
. "github.com/gin-gonic/gin"
"net/http"
)
func Pongo2() HandlerFunc {
return func(c *Context) {
c.Next()
templateName, templateNameError := c.Get("template")
templateNameValue, isString := templateName.(string)
if templateNameError == nil && isString {
templateData, templateDataError := c.Get("data")
var template = pongo2.Must(pongo2.FromCache(templateNameValue))
err := template.ExecuteWriter(getContext(templateData, templateDataError), c.Writer)
if err != nil {
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
}
}
}
}
func getContext(templateData interface{}, err error) pongo2.Context {
if templateData == nil || err != nil {
return nil
}
contextData, isMap := templateData.(map[string]interface{})
if isMap {
return contextData
}
return nil
}