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