Created
July 16, 2014 06:45
-
-
Save mopemope/51ea51b7a537a37c0dd5 to your computer and use it in GitHub Desktop.
Gin meets Pongo2 !
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/flosch/pongo2" | |
"github.com/gin-gonic/gin" | |
"net/http" | |
) | |
type pongoRender struct { | |
cache map[string]*pongo2.Template | |
} | |
func newPongoRender() *pongoRender { | |
return &pongoRender{map[string]*pongo2.Template{}} | |
} | |
func writeHeader(w http.ResponseWriter, code int, contentType string) { | |
if code >= 0 { | |
w.Header().Set("Content-Type", contentType) | |
w.WriteHeader(code) | |
} | |
} | |
func (p *pongoRender) Render(w http.ResponseWriter, code int, data ...interface{}) error { | |
file := data[0].(string) | |
ctx := data[1].(pongo2.Context) | |
var t *pongo2.Template | |
if tmpl, ok := p.cache[file]; ok { | |
t = tmpl | |
} else { | |
tmpl, err := pongo2.FromFile(file) | |
if err != nil { | |
return err | |
} | |
p.cache[file] = tmpl | |
t = tmpl | |
} | |
writeHeader(w, code, "text/html") | |
return t.ExecuteRW(w, ctx) | |
} | |
func main() { | |
r := gin.Default() | |
r.HTMLRender = newPongoRender() | |
r.GET("/index", func(c *gin.Context) { | |
name := c.Request.FormValue("name") | |
ctx := pongo2.Context{ | |
"title": "Gin with pongo2 !", | |
"name": name, | |
} | |
c.HTML(200, "index.html", ctx) | |
}) | |
// Listen and server on 0.0.0.0:8080 | |
r.Run(":8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The interfaces Gin provides for a custom template renderer have changed a little, so this won't work anymore with the latest version of Gin.
Also, you can use pongo2.FromCache() instead of pongo2.FromFile() which means you don't need to maintain your own cache, also it's thread safe... this doesn't really look thread safe to me.