From 8abf6c96b7beaba8795fe8de7ccc10dfafb06594 Mon Sep 17 00:00:00 2001 From: Darko Luketic Date: Mon, 21 Nov 2022 14:01:03 +0100 Subject: [PATCH] added v6 --- v6/render.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 v6/render.go diff --git a/v6/render.go b/v6/render.go new file mode 100644 index 0000000..286bd59 --- /dev/null +++ b/v6/render.go @@ -0,0 +1,52 @@ +package ginpongo2 + +import ( + "fmt" + "net/http" + + "github.com/flosch/pongo2/v6" + "github.com/gin-gonic/gin/render" +) + +var Suffix = ".html.twig" + +type Pongo struct { + set *pongo2.TemplateSet +} + +func (p *Pongo) Instance(name string, data interface{}) render.Render { + r := new(PongoRenderer) + tpl, e := p.set.FromCache(fmt.Sprintf("%s%s", name, Suffix)) + if e != nil { + panic(e) + } + r.tpl = tpl + r.data = data + return r +} + +type PongoRenderer struct { + tpl *pongo2.Template + data interface{} +} + +func (r *PongoRenderer) Render(w http.ResponseWriter) error { + if r.data == nil { + r.data = make(pongo2.Context) + } + d := r.data.(pongo2.Context) + return r.tpl.ExecuteWriter(d, w) +} + +func (r *PongoRenderer) WriteContentType(w http.ResponseWriter) { + if v := w.Header().Get("content-type"); len(v) == 0 { + w.Header().Set("content-type", "text/html; charset=utf8") + } +} + +func New(debug bool, loaders ...pongo2.TemplateLoader) *Pongo { + p := new(Pongo) + p.set = pongo2.NewSet("html", loaders...) + p.set.Debug = debug + return p +}